Regex

메타 문자: 원래 그 문자가 가진 뜻이 아니라 특별한 의미를 가진 문자

. ^ $ + ? { } [ ] \ | ( )

[a-b]: a~b

a.b: 사이에 줄바꿈을 제외한 모든 문자와 매치

ca*t: 0번 반복 포함

ca+t: n번 반복

ca{m, n}t: [2, 5]

ab?c: ? == {0, 1}

import re
 
p = re.compile('[a-z]+')
m = p.match('python')
print(m) # match = 'python'
print(m.group()) # python
print(m.start()) # 0
print(m.end()) # 6
print(m.span()) # (0, 6)
 
m = p.search('3 python')
print(m) # match = 'python'
 
m = p.findall('life is too short')
print(m) # ['list', 'is', 'too', 'short']

compile option

import re
 
p = re.compile('a.b', re.S) # re.DOTALL
p = re.compile('[a-z]', re.I) # re.IGNORECASE
p = re.compile("^python\s\w+", re.M) # re.MULTILINE
p = re.compile(r'&[#](0[0-7]+|[0-9]+|x[0-9a-fA-F]+);')
p = re.compile(r"""
	&[#]
   (0[0-7]+
   |[0-9]+
   |x[0-9a-fA-F]+
   )
   ;
   """, re.X) # re.VERBOSE
 

r”: raw string

\d: [0-9] \D: [^0-9] \s: [ \t\n\r\f\v] \S: [^ \t\n\r\f\v] \w: [a-zA-Z0-9_] \W: [^a-zA-Z0-9_]

|: or

^: 처음과 일치

$: 마지막에 일치

\b: 공백

\A: ^와 다르게 줄과는 상관없이 전체 문자열의 처음하고만 매치

Grouping

import re
 
p = re.compile('(ABC)+')
m = p.search('ABCABCABC OK?')
print(m) # match='ABCABCABC'
print(m.group()) # ABCABCABC
 
 
 
p = re.compile(r"(\w+)\s+\d+[-]\d+[-]\d+")
m = p.search("park 010-1234-1234")
print(m.group(1)) # park
# 인덱싱은 바깥쪽부터 시작해 안쪽으로 들어갈수록 증가
 
p = re.compile(r'(\b\w+)\s+\1')
p.search('Paris in the the spring').group() # 'the the'
# 정규표현식 안에서 재참조가 가능하다
 
p = re.compile(r"(P?<name>\w+)\s+\d+[-]\d+[-]\d+")
m = p.search("park 010-1234-1234")
print(m.group("name")) # park
# P?<foo>로 네이밍가능
 
p = re.compile(r'(P?<word>\b\w+)\s+(?P=word)')
p.search('Paris in the the spring').group() # 'the the'
# ?P=foo로 재참조 가능

전방탐색

import re
 
p = re.compile(".+(?=:)")
m = p.search("https://google.com")
print(m.group()) # https
# (?=foo) foo를 포함해서 검색하나 결과에는 포함하지 않는다
 
p = re.compile(".*[.](?!bat$).*$", re.M)
l = p.findall("""
			 autoexec.exe
			 autoexec.bat
			 autoexec.jpg
			  """)
print(1) # autoexec.exe, autoexec.jpg

문자열 바꾸기

import re
 
p = re.compile('(blue|white|red)')
p.sub('color', 'blue socks and red shoes') # 'color socks and color shoes'
 

greedy and non-greedy

import re
 
s = '<html><head><title>Title<\title>'
len(s) # 32
print(re.match('<.*>', s).span()) # (0, 32)
print(re.match('<.*>', s).group()) # <html><head><title>Title<\title>
print(re.match('<.*?>', s).group()) # <html>

참고자료: