Regular Expression; 정규표현식

주제무·2022년 5월 12일
0

Reference
https://docs.python.org/3/library/re.html
https://wikidocs.net/4308#findall

Regular Expression; regex

Loading Library

import re

Basic implementation

  1. Source 문자열의 Pattern을 찾아 정의하고 -> .compile()
  2. 그 Pattern을 처리한다!
    꼭 compile부터 할 필요는 없다. 인수에 패턴을 앞에 추가하면 된다.

Meta characters

[ ] : 문자 클래스
- : 범위
. : 하나의 모든 문자; \n을 제외하나 re.DOTALL을 통해 \n도 포함 가능; [.]은 문자 .을 의미
? + * : 0~1회, 1~회, 0~회 반복
{m, n} : m~n회 반복
^ : not

자주 사용되는 표현 대체

\d : [0-9]
\D : [^0-9]
\w : [a-zA-Z0-9_]
\W : [^a-zA-Z0-9_]

Method

  1. search
  2. match
  3. findall
  4. split
  5. sub
re.search(sentence)
# return Match object or None

match

첫 문자부터 패턴을 만족시켜야 하는 것이 search와 다르다.

re.match(sentence)
# return Match object or None

search and match method is used in if statement:

Match Object

Match objects always have a boolean value of True. Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement:

+ Match.group()은 object의 패턴을 출력

findall

패턴을 만족하는 모든 문자열을 패턴별로 나누어 리스트에 저장, 출력

re.findall(sentence)
# return list

추가할 사항
http://regexp.elex.pe.kr/regular-expression

0개의 댓글