상세 컨텐츠

본문 제목

Regular Expression 기초

Python

by techbard 2015. 7. 29. 16:23

본문

반응형
  • Very powerful method of matching patterns in text
  • Implemented in Python with the "re" module

# 문자열 search - 매칭

import re

ws = ['waterworld', 'watermelon', 'wakeboard']


for w in ws:

    if re.search('waterm', w):

        print(w)


결과)

watermelon


# 문자열 search - or 매칭

import re

ws = ['waterworld', 'watermelon', 'wakeboard']


for w in ws:

    if re.search('water|wake', w):

        print(w)


결과)

waterworld

watermelon

wakeboard


# 문자열 search - exact 매칭

import re

ws = ['waterworld', 'watermelon', 'wakeboard']


for w in ws:

    match = re.search('water|wake', w)

    if match:

        print(match.group())


결과)

water

water

wake


# 문자열 replace - sub() 메쏘드 사용

import re

ws = ['waterworld', 'watermelon', 'wakeboard']


for w in ws:

    print(re.sub('wa', '##', w))


결과)

##terworld

##termelon

##keboard


# 문자열 replace - match 객체의 요소를 스트링 교체

import re

ws = ['waterworld', 'watermelon', 'wakeboard']


for w in ws:

    match = re.search('wa', w)

    if match:

        print(w.replace(match.group(), '##'))


결과)

##terworld

##termelon

##keboard


# 매번 re 객체를 생성하지 않고 한 번만 생성해 놓고 계속 사용하는 방법 (대소문자 무시 옵션)

import re

ws = ['waterworld', 'watermelon', 'WAkeboard']


pattern = re.compile('wa', re.IGNORECASE)

for w in ws:

    if re.search(pattern, w):

        print(w)


결과)

waterworld

watermelon

WAkeboard


# re.compile() 메쏘드를 이용한 replace

import re

ws = ['waterworld', 'watermelon', 'WAkeboard']


pattern = re.compile('wa', re.IGNORECASE)

for w in ws:

    if re.search(pattern, w):

        print(re.sub(pattern, '##', w))


결과)

##terworld

##termelon

##keboard


반응형

관련글 더보기

댓글 영역