Data Engineering/python

EP09 | Python 심화 개념 #3 | 정규표현식(Regex)과 문자열 처리

ygtoken 2025. 3. 19. 22:43
728x90

이 글에서 다루는 개념

Python에서 **정규표현식(Regular Expression, Regex)**은 문자열을 효율적으로 검색하고 처리하는 강력한 도구입니다.
이번 글에서는 다음 내용을 학습합니다.

  • 정규표현식(Regex)의 기본 개념과 사용법
  • Python의 re 모듈 활용
  • 주요 정규표현식 패턴 (. * + ? ^ $ 등)
  • 문자열 찾기, 변경, 추출하는 방법

1️⃣ 정규표현식(Regex)란?

정규표현식은 특정 패턴을 가진 문자열을 검색하고 조작하는 데 사용됩니다.

📌 정규표현식 활용 예시

  • 이메일 주소, 전화번호, 우편번호 등 패턴 검증
  • 특정 단어 찾기 및 교체
  • 로그 파일에서 특정 패턴 검색

Python에서는 re 모듈을 사용하여 정규표현식을 다룰 수 있습니다.

import re

text = "Hello, my email is example@email.com"
pattern = r"\w+@\w+\.\w+"  # 이메일 형식

match = re.search(pattern, text)
if match:
    print("이메일 찾음:", match.group())  # example@email.com

 

📌 정규표현식 주요 함수 (re 모듈)

 

함수 설명
re.search(pattern, text) 첫 번째 일치하는 문자열 찾기
re.findall(pattern, text) 모든 일치하는 문자열 찾기 (리스트 반환)
re.match(pattern, text) 문자열의 시작 부분에서 패턴 확인
re.sub(pattern, repl, text) 일치하는 문자열 변경

2️⃣ 정규표현식 기초 패턴

🔹 기본 메타 문자

  

기호 의미 예제 (re.search())
. 임의의 한 문자 "h.t" → "hat", "hit"
* 0개 이상 반복 "ab*c" → "ac", "abc", "abbc"
+ 1개 이상 반복 "ab+c" → "abc", "abbc" (❌ "ac")
? 0개 또는 1개 존재 "colou?r" → "color", "colour"
^ 문자열 시작 "^Hello" → "Hello world"
$ 문자열 끝 "world$" → "Hello world"
\d 숫자 ([0-9]) "\d+" → "123"
\w 문자, 숫자, _ ([a-zA-Z0-9_]) "\w+" → "hello123"
\s 공백 문자 ( , \t, \n) "\s+" → " "
import re

text = "Python 3.9 is awesome!"
pattern = r"\d\.\d"  # 숫자.숫자 (버전 번호)
match = re.search(pattern, text)

print(match.group())  # 3.9

3️⃣ 문자열 찾기와 변경하기

🔹 re.findall() - 모든 패턴 찾기

import re

text = "My phone numbers are 010-1234-5678 and 02-987-6543."
pattern = r"\d{2,3}-\d{3,4}-\d{4}"  # 전화번호 패턴

matches = re.findall(pattern, text)
print(matches)  # ['010-1234-5678', '02-987-6543']

🔹 re.sub() - 문자열 변경

import re

text = "My email is example@email.com"
pattern = r"\w+@\w+\.\w+"  # 이메일 패턴
new_text = re.sub(pattern, "hidden@email.com", text)

print(new_text)  # My email is hidden@email.com

📌 응용 예제: 숫자만 추출

text = "Product ID: A123, B456, C789"
numbers = re.findall(r"\d+", text)
print(numbers)  # ['123', '456', '789']

📌 실전 문제: 정규표현식 연습하기


문제 1: 특정 단어 찾기 (re.search())

📌 문장에서 "Python"이라는 단어가 있는지 확인하고 출력하세요.

import re
text = "I love Python programming!"
# 🔽 여기에 코드 작성
import re

text = "I love Python programming!"
pattern = r"Python"

match = re.search(pattern, text)
if match:
    print("단어 찾음:", match.group())  # Python

문제 2: 모든 이메일 주소 찾기 (re.findall())

📌 문장에서 이메일 주소를 모두 찾아 출력하세요.

import re
text = "Contact me at example@email.com or support@domain.org."
# 🔽 여기에 코드 작성
import re

text = "Contact me at example@email.com or support@domain.org."
pattern = r"\w+@\w+\.\w+"

emails = re.findall(pattern, text)
print(emails)  # ['example@email.com', 'support@domain.org']

문제 3: 전화번호 형식 변경 (re.sub())

📌 문장에서 전화번호의 -를 공백( )으로 변경하세요.

import re
text = "My phone is 010-1234-5678 and 02-987-6543."
# 🔽 여기에 코드 작성
import re

text = "My phone is 010-1234-5678 and 02-987-6543."
pattern = r"-"
new_text = re.sub(pattern, " ", text)

print(new_text)  # My phone is 010 1234 5678 and 02 987 6543.

문제 4: 숫자만 추출 (re.findall())

📌 문장에서 모든 숫자를 추출하여 리스트로 저장하세요.

import re
text = "Order #12345, Product ID: 67890"
# 🔽 여기에 코드 작성
import re

text = "Order #12345, Product ID: 67890"
pattern = r"\d+"

numbers = re.findall(pattern, text)
print(numbers)  # ['12345', '67890']

 

 

728x90