나의 개발일지

[Python] 정규식 본문

백준

[Python] 정규식

YoonJuHan 2023. 6. 14. 15:18

정규식 사용 방법들

# 정규식 모듈
import re

# re.search()를 find() 처럼 쓰기
hand = open('mbox-short.txt')
for line in hand:
    line = line.rstrip()
    if re.search('From: ', line): # 검색대상 line
        print(line)

# From: 으로 시작하는 줄 찾기 ^ = 시작
hand = open('mbox-short.txt')
for line in hand:
    line = line.rstrip()
    if re.search('^From: ', line):
        print(line)

# 특수 지정 문자
# . = 어떤 문자가 와도 상관없다는 뜻
# * = 몇 번 와도 상관없다는 뜻
# ^X.*: = X 로 시작하고 어떤 문자든 몇 번이 나와도 상관없고 :으로 끝남
# hand = open('mbox-short.txt')
# for line in hand:
#     line = line.rstrip()
#     if re.search('^X.*: ', line):
#         print(line)


# X-로 시작 공백을 제외한 모든 것이 한 번 이상 올 수 있고 :로 끝남
# \s = 공백이 아닌 문자
hand = open('mbox-short.txt')
for line in hand:
    line = line.rstrip()
    if re.search('^X-\S+', line):
        print(line)

print("------------------------------------")

# re.search() 는 해당 문자열이 대상 정규식을 만족시키는지를 True/False로 리턴
# 매칭된 문자열을 추출하고 싶으면 re.findall() 사용 (리스트를 리턴)
x = 'My 2 favorite numbers are 19 and 42'
y = re.findall('[0-9]+', x) # 0부터 9까지 숫자가 하나 이상
print(y) # ['2', '19', '42']

# * 과 + 는 가장 길게 매칭되는 경우를 검색
x = 'From: Using the : character'
y = re.findall('^F.+:', x)
print(y) # ['From: Using the :']

# ?를 붙여주면 가장 짧은 경우를 검색
x = 'From: Using the : character'
y = re.findall('^F.+?:', x)
print(y) # ['From:']

# 한 개 이상의 빈칸이 아닌 문자
x = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
y = re.findall('\S+@\S+', x)
print(y) # ['stephen.marquard@uct.ac.za']

# 괄호는 매칭에 비포함
# 추출될 문자열의 시작 지점과 끝 지점을 지정하는 역할
# From 으로 시작하는 문자열 중 (\S+@\S+)이 부분만 추출하겠다.
x = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
y = re.findall('^From (\S+@\S+)', x)
print(y) # ['stephen.marquard@uct.ac.za']


# @가 나올 때 까지 탐색하고 공백이 아닌 문자 몇개든 제한 없음
x = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
y = re.findall('@([^ ]*)', x)
print(y) # ['uct.ac.za']

# 
x = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
y = re.findall('^From .*@([^ ]*)', x)
print(y) # ['uct.ac.za']


# Spam 감지
hand = open('mbox-short.txt')
numlist = list()

for line in hand:
    line = line.rstrip()
    stuff = re.findall('^X-DSPAM-Confidence: ([0-9.]+)', line)
    if len(stuff) != 1 : continue
    num = float(stuff[0])
    numlist.append(num)

print('Maximum:', max(numlist))

# 이스케이프 문자
# 지정된 특수 문자를 그냥 문자 그대로 사용하고 싶으면 \를 붙임
x = 'We just received $10.00 for cookies.'
y = re.findall('\$[0-9.]+',x)
print(y)
Comments