에듀테크 프로젝트 대시보드
정규표현식 (re)
re 모듈로 패턴 검색·추출·치환. 패턴 문자열은 raw 문자열 r"..." 로 씁니다.
import re
re.search(r"\d+", "abc123def") # 첫 매치 → Match 객체 (없으면 None)
re.match(r"\d+", "123abc") # 문자열 "시작"에서만
re.fullmatch(r"\d+", "123") # 전체가 일치해야
re.findall(r"\d+", "a1b22c333") # => ['1', '22', '333']
re.finditer(r"\d+", text) # Match 객체 이터레이터
re.sub(r"\s+", " ", messy) # 공백 정리
re.split(r"[,;]\s*", "a, b; c") # => ['a', 'b', 'c']m = re.search(r"(\d{4})-(\d{2})-(\d{2})", "날짜: 2024-01-15")
if m:
m.group(0) # '2024-01-15' (전체)
m.group(1) # '2024'
m.groups() # ('2024', '01', '15')
m.start(), m.end()
# 이름 있는 그룹
m = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})", s)
m.group("year")
m.groupdict() # {'year': '2024', 'month': '01'}| 패턴 | 의미 |
|---|---|
. | 임의의 한 글자 (개행 제외) |
\d \w \s | 숫자 / 단어문자 / 공백 (대문자는 여집합) |
^ $ | 문자열(줄) 시작 / 끝 |
* + ? | 0+ / 1+ / 0~1회 |
{n,m} | n~m회 |
[abc] [^abc] | 문자 집합 / 부정 |
(...) (?:...) | 그룹 캡처 / 비캡처 |
a|b | 택일 |
\b | 단어 경계 |
re.findall(r"<.*>", "<a><b>") # => ['<a><b>'] (탐욕적)
re.findall(r"<.*?>", "<a><b>") # => ['<a>', '<b>'] (최소, ? 추가)
re.sub(r"\d+", "#", "a1b22") # => 'a#b#' pat = re.compile(r"^\d{3}-\d{4}$") # 반복 사용 시 미리 컴파일
pat.match("123-4567")
re.search(r"hello", text, re.IGNORECASE) # re.I
re.findall(r"^\w+", text, re.MULTILINE) # re.M — ^ 가 각 줄 시작
re.search(r"a.b", text, re.DOTALL) # re.S — . 가 개행도 포함
# sub 에 함수 사용
re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "a1 b2") # => 'a2 b4' in, str.find, startswithhtml.parser, json, csv)re.VERBOSE 로 주석 달기