정규표현식

ai_lim·2021년 12월 30일
0

파이썬 기초

목록 보기
3/6

정규표현식은 언제 필요할까?
주민등록번호,전화번호,이메일 등 패턴화된 문자열에 정규표현식을 사용하면 좋다!

정규표현식을 사용하는 순서

1.패턴정의방식

  • ? : 0회 또는 1회 반복 *: 0회 이상 반복 + : 1회 이상 반복
  • {m, n} : m ~ n
  • \d : 숫자, [0-9]와 동일
  • \w : [a-zA-Z0-9_]와 동일
  • \s : 공백 문자, [ \t\n\r\f\v]와 동일
  • \b : 단어 경계

등등

2.처리방식

search(),match(),findall(),split(),sub()

search나 match가 리턴하는 group()

예제

text의 내용에서 1000년부터-2999년까지의 년도를 찾고싶다

text =The first season of America Premiere League was played in 1993.
The second season was played in 1995 in South Africa.
Last season was played in 2019 and won by Chennai Super Kings (CSK).
CSK won the title in 2000 and 2002 as well.
Mumbai Indians (MI) has also won the title 3 times in 2013, 2015 and 2017.

1.찾고자하는 패턴을 정의한다
([1-2]\d\d\d ->1번째숫자는 1,2로 고정 나머지숫자는 0-9까지 아무숫자)
pattern=re.compile('[1-2]\d\d\d')

2.일치하는 패턴을 모두 찾아서 반환한다
pattern.findall(text)

text = """
The first season of America Premiere League was played in 1993.
The second season was played in 1995 in South Africa.
Last season was played in 2019 and won by Chennai Super Kings (CSK).
CSK won the title in 2000 and 2002 as well.
Mumbai Indians (MI) has also won the title 3 times in 2013, 2015 and 2017.
"""
pattern = re.compile("[1-2]\d\d\d")
pattern.findall(text)

0개의 댓글