[Python] 정규 표현식(RE, regex)

김찬미·2024년 7월 19일
0

Python

목록 보기
5/7

정규 표현식이란?

정규 표현식(Regular Expression, regex)은 문자열에서 특정 패턴을 찾거나, 매칭하거나, 조작할 때 사용하는 강력한 도구이다. 정규 표현식은 다양한 프로그래밍 언어에서 지원하며, 파이썬에서는 re 모듈을 통해 사용할 수 있다.

🔍 정규 표현식의 개념

  • 패턴: 정규 표현식은 특정 문자열 패턴을 정의한다.
  • 매칭: 패턴을 사용하여 문자열에서 일치하는 부분을 찾는다.

🔧 파이썬의 re 모듈

파이썬에서 정규 표현식을 사용하기 위해 re 모듈을 임포트해야 한다.

import re

1) 📚 정규 표현식의 기본 구성 요소

1-1) 메타 문자

  • .: 임의의 한 문자와 일치
  • ^: 문자열의 시작
  • $: 문자열의 끝
  • *: 0회 이상 반복
  • +: 1회 이상 반복
  • ?: 0회 또는 1회
  • {n}: n회 반복
  • {n,}: n회 이상 반복
  • {n,m}: n회 이상 m회 이하 반복
  • []: 문자 집합
  • |: OR 연산자
  • (): 그룹

1-2) 예제 패턴

  • \d: 숫자와 일치
  • \D: 숫자가 아닌 문자와 일치
  • \s: 공백 문자와 일치
  • \S: 공백이 아닌 문자와 일치
  • \w: 단어 문자 (알파벳 + 숫자 + _)와 일치
  • \W: 단어 문자가 아닌 것과 일치

2) 🔢 파이썬 정규 표현식 함수

2-1) 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')

2-2) 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')

2-3) re.findall()

문자열에서 패턴과 일치하는 모든 부분을 리스트로 반환합니다.

import re

pattern = r'\d+'
text = 'abc123def456'
matches = re.findall(pattern, text)
print('Matches found:', matches)

2-4) re.finditer()

문자열에서 패턴과 일치하는 모든 부분을 반복 가능한 객체로 반환합니다. 각 항목은 Match 객체입니다.

import re

pattern = r'\d+'
text = 'abc123def456'
matches = re.finditer(pattern, text)
for match in matches:
    print('Match found:', match.group())

2-5) re.sub()

문자열에서 패턴과 일치하는 부분을 다른 문자열로 치환합니다.

import re

pattern = r'\d+'
text = 'abc123def456'
result = re.sub(pattern, 'NUM', text)
print('Substitution result:', result)

2-6) re.compile()

정규 표현식을 컴파일하여 패턴 객체를 생성합니다. 이 객체는 여러 번 사용할 수 있으며 성능이 향상될 수 있습니다.

import re

pattern = re.compile(r'\d+')
text = 'abc123def456'
matches = pattern.findall(text)
print('Matches found:', matches)

2-7) re.split()

패턴에 따라 문자열을 분리하여 리스트로 반환합니다.

import re

pattern = r'\W+'  # 공백이나 구두점으로 분리
text = 'Hello, world! This is a test.'
result = re.split(pattern, text)
print('Split result:', result)

2-8) 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')

2-9) re.purge()

정규 표현식 캐시를 비웁니다. 일반적으로 사용자가 직접 호출할 필요는 없습니다.

import re

re.purge()
print('Cache purged')

2-10) re.escape()

문자열에서 정규 표현식의 메타 문자를 이스케이프 처리하여, 패턴으로 사용될 수 있도록 변환합니다.

import re

text = '100% sure!'
escaped_text = re.escape(text)
print('Escaped text:', escaped_text)

3) 💻 정규 표현식의 활용 예제

3-1) 이메일 주소 검증

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')

3-2) 전화번호 형식 변환

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)

3-3) HTML 태그 제거

import re

pattern = r'<.*?>'
html = '<html><body><h1>Title</h1></body></html>'
text = re.sub(pattern, '', html)
print('Text without HTML tags:', text)

4) 🧠 정규 표현식의 고급 기능

4-1) 그룹

그룹을 사용하여 일치하는 부분을 캡처할 수 있다.

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))

4-2) 비캡처 그룹

(?:...)를 사용하여 비캡처 그룹을 만들 수 있다.

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))

4-3) 전방 탐색과 후방 탐색

  • 전방 탐색 ((?=...)): 특정 패턴이 뒤따라야 함
  • 부정 전방 탐색 ((?!...)): 특정 패턴이 뒤따라서는 안 됨
  • 후방 탐색 ((?<=...)): 특정 패턴이 앞서야 함
  • 부정 후방 탐색 ((?<!...)): 특정 패턴이 앞서서는 안 됨
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())

마치며 🚀

이처럼 정규 표현식은 매우 강력한 도구로, 다양한 문자열 처리 작업에서 사용할 수 있다. 개념을 외우는 것도 중요하지만 무엇보다 정규 표현식은 다양한 예제를 통해 여러 번 실습하며 익혀야 할 것 같다.

profile
백엔드 개발자

0개의 댓글

관련 채용 정보