- re 모듈을 사용한다.
- 아나콘다 설치 시 해당 라이브러리가 자동 설치된다.
- 정규표현식을 이를 통해 컴파일 한다.
python
import re
p = re.compile('[a-z]')
정규식을 이용한 문자열 검색
- 4가지 메서드를 제공한다.
match(): 문자열의 처음부터 정규식과 매치되는지 조사한다.search(): 문자열 전체를 검색하여 정규식과 매치되는지 조사한다.findall(): 정규식과 매치되는 모든 문자열을 리스트로.finditer(): 정규식과 매치되는 모든 문자열을 반복 가능한 객체로.
python
import re
p = re.compile('[a-z]')
m1 = p.match("python")
print(m1)
m1.group()
m1.start()
m1.end()
m1.span()
python
m2 = p.search("python")
print(m2)
python
m3 = p.findall("python is the best language")
print(m3)
python
m4 = p.finditer("python is the best language")
print(m4)
모듈단위로 수행하기
re.compile을 줄여 쓸 수 있는 방법
python
# 기존 방식
re.compile() = p
print(p.match())
python
# 새 방식
m = re.match("[a-z]+", "python")
문자열 바꾸기
sub 메서드를 이용해 정규식과 매치되는 부분을 다른 문자로 바꿀 수 있음.
count 인자를 통해 바꾸기 횟수를 제어.
python
p = re.compile(('blue|white|red'))
p.sub('colour', 'blue socks and red shoes', count=1)