파이썬의 regex 정규표현식으로 내장 모듈인 re를 사용한다.
- \d - 숫자와 매치, [0-9]와 동일한 표현식이다.
- \D - 숫자가 아닌 것과 매치, [^0-9]와 동일한 표현식이다.
- \s - whitespace 문자와 매치, [ \t\n\r\f\v]와 동일한 표현식이다. 맨 앞의 빈 칸은 공백문자(space)를 의미한다.
- \S - whitespace 문자가 아닌 것과 매치, [^ \t\n\r\f\v]와 동일한 표현식이다.
- \w - 문자+숫자(alphanumeric)와 매치, [a-zA-Z0-9_]와 동일한 표현식이다.
- \W - 문자+숫자(alphanumeric)가 아닌 문자와 매치, [^a-zA-Z0-9_]와 동일한 표현식이다.
import re
re.findall('\d+', 'berry071212')
>>> ['071212']
s로 시작하는 문자열은 match 결과가 나온다.
s가 문자열에 있어도, 해당 문자열로 시작하지 않으면 결과가 나오지 않는다.
import re
print(re.match('s', 'song'))
print(re.match('s', 'sims'))
print(re.match('s', 'apple'))
print(re.match('s', 'asap'))
>>>
<re.Match object; span=(0, 1), match='s'>
<re.Match object; span=(0, 1), match='s'>
None
None
match는 해당 문자열로 시작하는 문자만 찾을 수 있지만,
search는 해당 문자열의 인덱스도 보여준다.
import re
print(re.search('s', 'song'))
print(re.search('s', 'sims'))
print(re.search('s', 'apple'))
print(re.search('s', 'asap'))
>>>
<re.Match object; span=(0, 1), match='s'>
<re.Match object; span=(0, 1), match='s'>
None
<re.Match object; span=(1, 2), match='s'>