Soy Library

[Python] 정규표현식 연습 (1) 본문

Study/Python

[Python] 정규표현식 연습 (1)

Soy_Hwang 2022. 11. 20. 23:22

정규표현식의 기초, 메타문자: [], Dot(.), 반복(*, +, {m,n}) , ?

- [abc] : 대괄호 안 문자들과 매치. 하이픈(-)을 이용하여 from-to도 가능.

- Dot(.) : 줄바꿈(\n)을 제외한 모든 문자와 매치. 또한 하나는 있어야 매치됨.

- 반복(*) : 0번 이상 반복되면 매치.

- 반복(+) : 1번 이상 반복되면 매치.

- 반복({m,n}) : m이상 n이하 반복되는 부분과 매치. 

- ? : 0회 또는 1회  == {m, n}

정규식을 이용한 문자열 검색

1. match

# match: 
p = re.compile('[a-z]+')  # a-z까지 어떠한 문자열이 한 번 이상 반복. 
m = p.match('python') ; print(m)
m = p.match('3 python') ; print(m)

# 결과
<re.Match object; span=(0, 6), match='python'>
None

2. search

# search: 일치하는 부분이 있다면 출력
p = re.compile('[a-z]+')  # a-z까지 어떠한 문자열이 한 번 이상 반복. 
m = p.search('python') ; print(m)
m = p.search('3 python') ; print(m)

# 결과
<re.Match object; span=(0, 6), match='python'>
<re.Match object; span=(2, 8), match='python'>

3. findall

# findall: 일치하는 string을 list로 출력해줌. 
p = re.compile('[a-z]+')
m = p.findall('Life is too short 33') ; print(m)

# 결과
['ife', 'is', 'too', 'short']

4. finditer

# finditer: iterator object를 출력해줌.
p = re.compile('[a-z]+')
m = p.finditer('Life is too short 33') ; print(m) # 대문자는 match안되는 것을 볼 수 있음. 

for r in m :
    print(r) # match되는 문자열을 match 객체로 return해줌. 
    
# 결과
<callable_iterator object at 0x0000027FD1DC0550>
<re.Match object; span=(1, 4), match='ife'>
<re.Match object; span=(5, 7), match='is'>
<re.Match object; span=(8, 11), match='too'>
<re.Match object; span=(12, 17), match='short'>

Match 객체는 네 가지 method

- group() : 매치된 문자열 리턴.

- start() : 매치된 문자열 시작 위치 리턴

- end() : 매치된 문자열의 끝 위치 리턴

- span() : 매치된 문자열의 (시작, 끝) 인덱스에 해당되는 튜플 리턴

p = re.compile('[a-z]+')
m = p.match('python') ; print(m)

print(m.group())
print(m.start()) 
print(m.end())
print(m.span())

# 결과
<re.Match object; span=(0, 6), match='python'>
python
0
6
(0, 6)

컴파일 옵션: DOTALL, IGNORECASE, MULTILINE, VERBOSE

1. DOTALL, S : 줄바꿈문자(\n)도 포함하게 하는 옵션

# DOTALL, S
p = re.compile('a.b')
m = p.match('a\nb')  # dot에는 줄바꿈 문자를 포함하지 않기 때문에 match가 되지 않음
print(m)

p = re.compile('a.b', re.DOTALL) # 줄바꿈 문자도 포함하도록 하는 옵션
m = p.match('a\nb')
print(m)  

p = re.compile('a.b', re.S) # 똑같음
m = p.match('a\nb')
print(m)  

# 결과
None
<re.Match object; span=(0, 3), match='a\nb'>
<re.Match object; span=(0, 3), match='a\nb'>

2. IGNORECASE, I : 대소문자 구분 안하게 하는 옵션

# IGNORECASE, I
p = re.compile('[a-z]') # 원래 소문자 알파벳만 추출하는 표현식
print(p.match('python'))
print(p.match('Python'))
print(p.match('PYTHON'))
print(p.match('What is Python?'))
print(p.match('pythonhello'))
print(p.match('what is Python?'))

p = re.compile('[a-z]', re.I) # 대소문자 구분 ㄴ 
print(p.match('python'))
print(p.match('Python'))
print(p.match('PYTHON'))
print(p.match('What is Python?'))

# 결과 
<re.Match object; span=(0, 1), match='p'>
None
None
None
<re.Match object; span=(0, 1), match='p'>
<re.Match object; span=(0, 1), match='w'>
<re.Match object; span=(0, 1), match='p'>
<re.Match object; span=(0, 1), match='P'>
<re.Match object; span=(0, 1), match='P'>
<re.Match object; span=(0, 1), match='W'>

3. MULTILINE, M : 줄바꿈 되어있는 부분을 문장의 시작으로 보고 표현식 적용 가능하게 함

# MULTILINE, M
p = re.compile('^python\s\w+')  # \s는 공백, \w는 알파벳, 숫자, _중의 한 문자 ^는 맨 처음에 시작하는 것. 
data = '''python one
life is too short
python two
you need python
python three
'''
print(p.findall(data)) 

p = re.compile('^python\s\w+', re.M)  # \s는 공백, \w는 알파벳, 숫자, _중의 한 문자 ^는 맨 처음에 시작하는 것. 
print(p.findall(data))  # multiline 옵션 적용.

# 결과
['python one']
['python one', 'python two', 'python three']

4. VERBOSE: 긴 정규표현식이 있을 때, 나눠서 쓰게 할 수 있는 옵션. 

 

 

Reference 

유튜버 '조코딩' 님의 영상

https://wikidocs.net/4308

 

07-2 정규 표현식 시작하기

[TOC] ## 정규 표현식의 기초, 메타 문자 정규 표현식에서 사용하는 메타 문자(meta characters)에는 다음과 같은 것이 있다. > ※ 메타 문자란 원래 그 …

wikidocs.net