08 regular expression

Regular Expression

  • 정규표현식(正規表現式, Regular Expression)은 문자열을 처리하는 방법 중의 하나로 특정한 조건의 문자를 '검색'하거나 '치환'하는 과정을 매우 간편하게 처리 할 수 있도록 하는 수단이다.
  • 정규표현식에서 사용하는 기호를 Meta문자라고 합니다. Meta문자는 표현식 내부에서 특정한 의미를 갖는 문자를 말하며, 중요 Matching Meta문자의 종류로는 다음과 같다.

    • .(dot):줄바꿈 문자를 제외한 모든 문자와 매치됨(the default mode, this matches any character)
    • ^(carot):문자열의 시작과 매치됨(Matches the start of the string)
    • \$:문자열의 마지막과 매치됨(Matches the end of the string)
    • []:"["와"]" 사이의 문자들 중에 하나이어야 함.(Used to indicate a set of characters)
    • '[0-9]', '\d':숫자를 의미
    • '[a-zA-Z]','\w':문자를 의미
  • Python에서는 re모듈을 사용하여 정규표현식을 지원한다.Re docs

  • re모듈의 주요메소드는 다음과 같다.
    • re.compile():pattern을 컴파일하여 정규식 객체를 반환
    • re.match():Sring의 시작부분부터 pattern이 존재하는지 검사하여 객체를 반환
    • re.search():Sring의 전체에 대해서 pattern이 존재하는지 검사하여 객체를 반환
    • re.sub():string에서 pattern과 일치하는 부분에 대하여 repl로 교체하여 결과 문자열을 반환
    • re.split():pattern을 구분자로 string을 분리하여 리스트로 반환

re.search()

In [1]:
import re
print(bool(re.search('.',"abc")))
print(bool(re.search('[.]',"abc")))
print(bool(re.search('[c]',"abc")))
print(bool(re.search('^a',"abc")))
print(bool(re.search('^c',"abc")))
print(bool(re.search('c',"abc")))
print(bool(re.search('c$',"abc")))
print(bool(re.search('[. a]',"abc")))
True
False
True
True
False
True
True
True

re.match()

In [2]:
print(bool(re.match('.',"abc")))
print(bool(re.match('[.]',"abc")))
print(bool(re.match('[c]',"abc")))
print(bool(re.match('^a',"abc")))
print(bool(re.match('^c',"abc")))
print(bool(re.match('c',"abc")))
print(bool(re.match('c$',"abc")))
print(bool(re.match('[. a]',"abc")))
True
False
False
True
False
False
False
True

re.split

In [3]:
re.split('[:. ]+',"apple Orage:banna tomaao")
Out[3]:
['apple', 'Orage', 'banna', 'tomaao']
In [4]:
bool(re.match('[:. ]',"apple Orage:banna tomaao"))
Out[4]:
False
In [5]:
bool(re.search('[:. ]',"apple Orage:banna tomaao"))
Out[5]:
True
In [6]:
# re.split()
In [7]:
re.split('([:. ])',"apple Orage:banna tomaao")
Out[7]:
['apple', ' ', 'Orage', ':', 'banna', ' ', 'tomaao']
In [8]:
ab = re.split('[:. ]',"apple Orage:banna tomaao")
In [9]:
import re
str1 = "ab34ef56"
(re.split('[0-9]', str1))
Out[9]:
['ab', '', 'ef', '', '']
In [10]:
(re.split('[a-zA-Z]', str1))
Out[10]:
['', '', '34', '', '56']

sub

In [11]:
re.sub('-',"@","A&B-C*454")
Out[11]:
'A&B@C*454'
In [12]:
re.sub("[(*&]","","A&B-C*454")
Out[12]:
'AB-C454'


© 2017. All rights reserved.

Powered by ZooFighter v0.12