복잡한 문자열을 처리할 때 사용하는 기법으로 줄여서 '정규식'이라고도 한다. (파이썬만의 고유한 문법은 아니지만 알아두면 유용하게 사용할 수 있고 URL을 공부할 때 갑자기 등장하기 때문에 미리 공부해두기로 한다.)
참고 👉 점프투파이썬
[abc]
: a, b, c 중 문자 한개와의 매치
[a-z]
: 소문자 알파벳 모두
[a-zA-Z]
: 알파벳 모두
[0-9]
: 숫자 모두
\d
: 숫자와 매치
\s
: 공백과 매치
\w
: 문자 + 숫자와 매치
🍟 \n
을 제외한 모든 문자
a.b
: a + '모든 문자' + b
a[.]b
: a + . + b
🍟 *
바로 앞에 있는 문자가 0부터 무한대로 반복
ca*t
: c + a(0~무한반복) + t
🍟 +
바로 앞에 있는 문자가 1부터 무한대로 반복
ca+t
: "c + a(1번 이상 반복) + t
ca{2}t
: c + a(2번 반복) + t
ca{2,5}t
: c + a(2~5회 반복) + t
ab?c
: a + b(0~1회 반복) + c
Example
👉 regex101 정규표현식을 연습할 수 있는 사이트
import re
re
모듈의 함수 🧡findall()
: Returns a list containing all matches
🍟결과값을 리스트 형태로 반환한다.
search()
: Returns a Match object if there is a match anywhere in the string
match()
: Returns a Match object if there is a match in the beginning of the string
🍟search()는 문자열 전체에서 패턴을 찾고, match()는 문자열 도입에서 패턴을 찾는다. (match()
는 스크립트의 중간에 있는 패턴을 찾을 수 없다.)
🍟결과값을 re모듈 형식으로 반환하기때문에 group()
함수를 이용해 결과값을 나타낸다.
split()
: Returns a list where the string has been split at each match
sub()
: Replaces one or many matches with a string
import re
f = open('friends101.txt', 'r')
script = f.read()
line = re.findall('Monica:.+',script)
for x in line :
print(x)
f.close()
#새로운 파일로 저장
f = open('monica_script.txt', 'w')
monica = ''
for x in line :
monica += x + '\n'
f.write(monica)
f.close
결과
Monica: There's nothing to tell! He's just some guy I work with! Monica: Okay, everybody relax. This is not even a date. It's just two people going out to dinner and- not having sex. Monica: And they weren't looking at you before?! Monica: Are you okay, sweetie?