[Python] 정규표현식
Y
Yerim
- Python
p = re.compile('[a-z]+')
m = p.match("python")
print(m)# 축약
m = re.match('[a-z]+', "python")
print(m)Method | 목적 |
match() | 문자열의 처음부터 정규식과 매치되는지 조사 |
search() | 문자열 전체를 검사하여 정규식과 매치되는지 조사 |
findall() | 정규식과 매치되는 모든 문자열 substring을 리스트로 리턴 |
finditer() | 정규식과 매치되는 모든 문자열 substring을 반복 가능한 객체로 리턴 |
import re
# 네자리 번호
# abcd, book, desk
# ca?e -> 기억나는 번호
# care, cafe, case, cave -> 가능한 번호
# caae, cabe, cace ,cade, ... -> 너무 많다.
p = re.compile("ca.e")
# . (ca.e) : 하나의 문자를 의미 > care, cafe, case (O) | caffe (X)
# ^ (^de) : 문자열의 시작 > desk, destination (O) | fade (X)
# $ (se&) : 문자열의 끝 > case, base (O) | face (X)
def print_match(m):
if m:
print("m.group():", m.group()) # 일치하는 문자열 반환
print("m.string:", m.string) # 입력받은 문자열
print("m.start():", m.start()) # 일치하는 문자열의 시작 index
print("m.end():", m.end()) # 일치하는 문자열의 끝 index
print("m.span():", m.span()) # 일치하는 문자열의 시작/끝 index
else:
print("매칭되지 않음")
m = p.match("case")
# match: 주어진 문자열의 처음부터 일치하는지 확인
# careless는 care로 매체가 된다.
# print_match(m)
# print(m.group()) # 정규식과 매치되지 않으면 에러가 발생
m = p.search("good care") # search: 주어진 문자열 중에 일치하는게 있는지 확인
print_match(m)
# lst = p.findall("good care cafe") # findall: 일치하는 모든 것을 리스트 형태로 반환
# print(lst)m.group(): care
m.string: good care
m.start(): 5
m.end(): 9
m.span(): (5, 9)
# ['care', 'cafe']re.search('^Life', 'Life is too short') # 매치 - Match 객체
re.search('^Life', 'My Life') # 매치되지 않음 - Nonere.search('short$', 'Life is too short') # 매치 - Match 객체
re.search('short$', 'Life is too short, you need python') # 매치되지 않음 - nonep = re.compile('Crow|Servo')
m = p.match('CrosHellow')p = re.compile(r'\bclass\b')
p.search('no class at all')
p.search('the declassified algorithm')
p.search('one subclass is')group (인덱스) | 설명 |
group(0) | 매치된 전체 문자열 |
group(1) | 첫 번째 그룹에 해당되는 문자열 |
group(2) | 두 번째 그룹에 해당되는 문자열 |
group(3) | n 번쨰 그룹에 해당되는 문자열 |
