정규표현식
복잡한 문자열을 처리할 때 사용하는 기법, 모든 언어 공통
형식 : /[Pattern]/[Flag]
Pattern
Groups and Ranges
Character | 뜻 |
---|
| | 또는 |
() | 그룹 |
[] | 문자셋, 괄호안의 어떤 문자든 |
[^] | 부정 문자셋, 괄호안의 어떤 문자가 아닐때 |
(?:) | 찾지만 기억하지는 않음 |
Quantifiers
Character | 뜻 |
---|
? | 없거나 있거나 (zero or one) |
* | 없거나 있거나 많거나 (zero or more) |
+ | 하나 또는 많이 (one or more) |
{n} | n번 반복 |
{min,} | 최소 |
{min,max} | 최소, 그리고 최대 |
Character Classes
Character | 뜻 |
---|
. | 어떤 글자 (줄바꿈 문자 제외) |
\ | 특수 문자가 아닌 문자 |
\s | space 공백 |
\w | word 문자 |
\d | digit 숫자 |
\S | space 공백 아님 |
\W | word 문자 아님 |
\D | digit 숫자 아님 |
Boundary Type
Character | 뜻 |
---|
\b | 단어 경계 |
\B | 단어 경계가 아님 |
^ | 문장의 시작 |
$ | 문장의 끝 |
Flag
Character | 뜻 |
---|
g | global |
m | multiline |
i | case insensitive |
s | single line (dotall) |
u | unicode |
y | sticky |
with Python
re Module과 Pattern 객체 Method
import re
p = re.compile('[a-z]+')
m1 = p.match('3 python')
m2 = p.match('python')
m3 = p.search('3 python')
m4 = p.findall('life is too short')
m5 = p.finditer('life is too short')
print(f"m1 : {m1}")
print(f"m2 : {m2}")
print(f"m3 : {m3}")
print(f"m4 : {m4}")
print(f"m5 : {m5}")
for i in m5:
print(i)
p = re.compile('(blue|white|red)')
m = p.sub('colour', 'blue socks and red shoes')
print(m)
Match 객체 Method
p = re.compile('[a-z]+')
m = p.match('python')
print(m.group())
print(m.start())
print(m.end())
print(m.span())
Compile Option
p1 = re.compile('a.b')
p2 = re.compile('a.b', re.DOTALL)
print(p1.match('a\nb)
print(p2.match('a\nb')
p1 = re.compile('[a-z]+')
p2 = re.compile('[a-z]+', re.IGNORECASE)
print(p1.match('python'))
print(p1.match('Python'))
print(p1.match('PYTHON'))
print(p2.match('python'))
print(p2.match('Python'))
print(p2.match('PYTHON'))
p1 = re.compile("^python\s\w+")
p2 = re.compile("^python\s\w+", re.MULTILINE)
data = """python one
life is too short
python two
you need python
python three
"""
print(p1.findall(data))
print(p2.findall(data))
RegEx in Python
print(re.match('Crow|Servo', 'CrowHello'))
print(re.search('^Life', 'Life is too short'))
print(re.search('^Life', 'My Life'))
print(re.search('short$', 'Life is too short'))
print(re.search('short$', 'Life is too short, you need python'))
p = re.compile(r'\bclass\b')
print(p.search('no class at all'))
print(p.search('the declassified algorithm'))
print(p.search('one subclass is ...'))
p = re.compile('(ABC)+')
m = p.search('ABCABCABC OK?')
print(m)
print(m.group())
p = re.compile("(\w+)\s+\d+[-]\d+[-]\d+")
m = p.search("park 010-1234-1234")
print(m.group())
print(m.group(0))
print(m.group(1))
p = re.compile("(?P<name>\w+)\s+\d+[-]\d+[-]\d+")
m = p.search("park 010-1234-1234")
print(m.group("name"))
p1 = re.compile(".+:")
p2 = re.compile(".+(?=:)")
m1 = p1.search("http://google.com")
m2 = p2.search("http://google.com")
print(m1.group())
print(m2.group())
p1 = re.compile(".*[.](?!bat$).*$", re.M)
m1 = p1.findall("""
autoexec.exe
autoexec.bat
autoexec.jpg
""")
print(m1)
s = '<html><head><title>Title</title>'
print(re.match('<.*>', s).group())
print(re.match('<.*?>', s).group())
<참고>
드림코딩 정규표현식 Youtube 강좌
https://www.youtube.com/watch?v=t3M6toIflyQ&list=PL1-s2FQ4BBUO1VkRXlEsQSvOXKbmjEJgN&index=7
조코딩 파이썬 정규표현식의 기초와 활용 Youtube 강좌
https://www.youtube.com/watch?v=dTDoTR0MXjU&list=PL1-s2FQ4BBUO1VkRXlEsQSvOXKbmjEJgN&index=13