1. methods
re.match(pattern, string, flags)
re.search(pattern, string, flags)
re.findall(pattern, string, flags)
re.sub(pattern, repl, string, count, flags)
- repl : string or function. (치환 후의 문자열) or (matchObject -> 치환 후의 문자열).
- count는 최대 몇 개를 치환할지를 지정
- ex) 비밀번호 앞에 4자리만 보여주기
re.sub("^(\d{4})(\d+)", lambda m : m.group(1)+"*"*len(m.group(2)), password)
re.split(patter, string, maxsplit, flags) : maxsplit은 최대 몇 번 자를지 지정
2. match object
import re
matchObj = re.search('test', 'this is a test sentence.')
print(matchObj)
print(matchObj.group())
print(matchObj.start())
print(matchObj.end())
print(matchObj.span())
group()은 일치하는 패턴을 반환, groups는 캡쳐한 group tuple을 반환
findall은 캡쳐가 있다면 list of patterns가 아니라 list of group tuples를 반환
import re
matchObj = re.search('(\d{4})-(\d{1,2})-(\d{1,2})', '2018-3-4 2019-11-17')
print(matchObj)
print(matchObj.group())
print(matchObj.groups())
print("-"*30)
matchObj = re.findall('(\d{4})-(\d{1,2})-(\d{1,2})', '2018-3-4 2019-11-17')
print(matchObj)
3. \d, \D, \w, \W, \s, \S
\d : 숫자
\w : 영문 대소문자, 숫자, _(언더바), 한글(파이썬의 경우), ...
\s : space, \t, \n
\D : \d의 반대
\W : \w의 반대 (공백, 특수문자)
\S : \s의 반대
4. ^, $, \A, \Z
By default,
^, $ : 문자열의 시작과 끝에 매치
\A, \Z : 문자열의 시작과 끝에 매치
하지만 re.M 혹은 re.MULTILINE 플래그를 적용시키면,
^, $ : 행의 시작과 끝에 매칭
import re
print(re.findall('\Ahello', 'hello\nhello\nhello'))
print(re.findall('^hello', 'hello\nhello\nhello'))
print(re.findall('^hello', 'hello\nhello\nhello', re.MULTILINE))
Reference.
Python, Machine & Deep Learning
Python, Machine Learning & Deep Learning
greeksharifa.github.io
'프로그래밍 언어 > Python' 카테고리의 다른 글
파이썬 concatenation (0) | 2022.06.13 |
---|---|
파이썬 reduce (0) | 2022.06.12 |
파이썬 cmp_to_key (0) | 2022.06.10 |
파이썬 any, all (0) | 2022.06.10 |
파이썬 진법 변환 (0) | 2022.06.09 |