파이썬/파이썬(python) 초급

파이썬 정규표현식 모듈 re, re.sub, re.findall, re.search

Olivia-BlackCherry 2023. 5. 1. 04:19

정규표현식 regular expression 모듈인 re모듈은 python에서 문자열의 특정 패턴을 찾거나, 이를 변환하는 데 사용된다. 

're' 모듈은 많은 문자열 처리 작업을 수행한다. 

 

1. re.search()

문자열에서 정규식 패턴과 일치하는 첫 번째 위치를 찾음

import re

string = "The quick brown fox jumps over the lazy dog"
pattern = "quick"

match = re.search(pattern, string)

if match:
    print("Match found at index:", match.start())
else:
    print("Match not found")
Match found at index: 4

 

 

2. re.sub()

문자열에서 정규식과 일치하는 부분을 다른 문자열로 대체한다. 

import re

string = "The quick brown fox jumps over the lazy dog"
pattern = "lazy"
replacement = "sleepy"

new_string = re.sub(pattern, replacement, string)

print(new_string)
>>
The quick brown fox jumps over the sleepy dog

 

 

3. re.findall()

문자열에서 정규식 패턴과 일치하는 모든 부분을 찾아 리스트로 반환한다. 

import re

string = "The quick brown fox jumps over the lazy dog"
pattern = "[aeiou]"

matches = re.findall(pattern, string)

print(matches)

>>

['woo', 'woo', 'woo', 'woo']
str2= "How much wood would a woodchuck chuck, if a woodchuck could chuck wood?"
re.findall("woo", str2)

>>

['e', 'u', 'i', 'o', 'o', 'u', 'o', 'e', 'e', 'a', 'o']