정규 표현식(Regular Expression, regex)은 문자열에서 특정 패턴을 찾거나, 매칭하거나, 조작할 때 사용하는 강력한 도구이다. 정규 표현식은 다양한 프로그래밍 언어에서 지원하며, 파이썬에서는 re
모듈을 통해 사용할 수 있다.
re
모듈파이썬에서 정규 표현식을 사용하기 위해 re
모듈을 임포트해야 한다.
import re
.
: 임의의 한 문자와 일치^
: 문자열의 시작$
: 문자열의 끝*
: 0회 이상 반복+
: 1회 이상 반복?
: 0회 또는 1회{n}
: n회 반복{n,}
: n회 이상 반복{n,m}
: n회 이상 m회 이하 반복[]
: 문자 집합|
: OR 연산자()
: 그룹\d
: 숫자와 일치\D
: 숫자가 아닌 문자와 일치\s
: 공백 문자와 일치\S
: 공백이 아닌 문자와 일치\w
: 단어 문자 (알파벳 + 숫자 + _
)와 일치\W
: 단어 문자가 아닌 것과 일치re.match()
문자열의 시작 부분이 패턴과 일치하는지 검사합니다.
import re
pattern = r'\d+'
text = '123abc'
match = re.match(pattern, text)
if match:
print('Match found:', match.group())
else:
print('No match')
re.search()
문자열에서 패턴과 일치하는 부분을 검색합니다. 문자열의 어느 위치에서든 일치하는 부분을 찾습니다.
import re
pattern = r'\d+'
text = 'abc123'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
else:
print('No match')
re.findall()
문자열에서 패턴과 일치하는 모든 부분을 리스트로 반환합니다.
import re
pattern = r'\d+'
text = 'abc123def456'
matches = re.findall(pattern, text)
print('Matches found:', matches)
re.finditer()
문자열에서 패턴과 일치하는 모든 부분을 반복 가능한 객체로 반환합니다. 각 항목은 Match
객체입니다.
import re
pattern = r'\d+'
text = 'abc123def456'
matches = re.finditer(pattern, text)
for match in matches:
print('Match found:', match.group())
re.sub()
문자열에서 패턴과 일치하는 부분을 다른 문자열로 치환합니다.
import re
pattern = r'\d+'
text = 'abc123def456'
result = re.sub(pattern, 'NUM', text)
print('Substitution result:', result)
re.compile()
정규 표현식을 컴파일하여 패턴 객체를 생성합니다. 이 객체는 여러 번 사용할 수 있으며 성능이 향상될 수 있습니다.
import re
pattern = re.compile(r'\d+')
text = 'abc123def456'
matches = pattern.findall(text)
print('Matches found:', matches)
re.split()
패턴에 따라 문자열을 분리하여 리스트로 반환합니다.
import re
pattern = r'\W+' # 공백이나 구두점으로 분리
text = 'Hello, world! This is a test.'
result = re.split(pattern, text)
print('Split result:', result)
re.fullmatch()
문자열 전체가 패턴과 일치하는지 검사합니다. 전체가 일치하면 Match
객체를 반환하고, 그렇지 않으면 None
을 반환합니다.
import re
pattern = r'\d+'
text = '123'
match = re.fullmatch(pattern, text)
if match:
print('Full match found:', match.group())
else:
print('No full match')
re.purge()
정규 표현식 캐시를 비웁니다. 일반적으로 사용자가 직접 호출할 필요는 없습니다.
import re
re.purge()
print('Cache purged')
re.escape()
문자열에서 정규 표현식의 메타 문자를 이스케이프 처리하여, 패턴으로 사용될 수 있도록 변환합니다.
import re
text = '100% sure!'
escaped_text = re.escape(text)
print('Escaped text:', escaped_text)
import re
pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+'
email = 'test@example.com'
if re.match(pattern, email):
print('Valid email address')
else:
print('Invalid email address')
import re
pattern = r'(\d{3})-(\d{3})-(\d{4})'
text = 'My phone number is 123-456-7890'
result = re.sub(pattern, r'(\1) \2-\3', text)
print('Formatted phone number:', result)
import re
pattern = r'<.*?>'
html = '<html><body><h1>Title</h1></body></html>'
text = re.sub(pattern, '', html)
print('Text without HTML tags:', text)
그룹을 사용하여 일치하는 부분을 캡처할 수 있다.
import re
pattern = r'(\d+)-(\d+)-(\d+)'
text = '123-456-7890'
match = re.match(pattern, text)
if match:
print('Group 1:', match.group(1))
print('Group 2:', match.group(2))
print('Group 3:', match.group(3))
(?:...)
를 사용하여 비캡처 그룹을 만들 수 있다.
import re
pattern = r'(?:\d+)-(\d+)-(\d+)'
text = '123-456-7890'
match = re.match(pattern, text)
if match:
print('Group 1:', match.group(1))
print('Group 2:', match.group(2))
(?=...)
): 특정 패턴이 뒤따라야 함(?!...)
): 특정 패턴이 뒤따라서는 안 됨(?<=...)
): 특정 패턴이 앞서야 함(?<!...)
): 특정 패턴이 앞서서는 안 됨import re
# 전방 탐색 예제
pattern = r'\d+(?= dollars)'
text = 'I have 100 dollars'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
# 부정 전방 탐색 예제
pattern = r'\d+(?! dollars)'
text = 'I have 100 euros'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
이처럼 정규 표현식은 매우 강력한 도구로, 다양한 문자열 처리 작업에서 사용할 수 있다. 개념을 외우는 것도 중요하지만 무엇보다 정규 표현식은 다양한 예제를 통해 여러 번 실습하며 익혀야 할 것 같다.