초보개발자의 초보블로그
Hello World

Coding/Python

파이썬 정규식 기본(?)

Complish_dev 2021. 5. 4. 23:16
반응형
import re

# abcd, book, desk
# ca?e
# care, cafe, case, cave

p = re.compile("ca.e") 
# . (ca.e): 하나의 문자를 의미 > care, cafe, case (O) | caffe (X)
# ^ (^de) : 문자열의 시작 > desk, destination (O) | fade (X)
# $ (se$) : 문자열의 끝 > case, base (O) | face (X)

def print_match(m):
    if m:
        print("m.group():",m.group()) # 일치하는 문자열 반환
        print("m.string:",m.string) # 입력받은 문자열
        print("m.start():", m.start()) # 일치하는 문자열의 시작 index
        print("m.end():", m.end()) # 일치하는 문자열의 끝 index
        print("m.span():", m.span()) # 일치하는 문자열의 시작 / 끝 index
        
    else:
        print("매칭되지 않음")

# m = p.match("careless") # match : 주어진 문자열의 처음부터 일치하는지 확인
# print_match(m)

# m = p.search("good care") # search : 주어진 문자열 중에 일치하는게 있는지 확인
# print_match(m)

# lst = p.findall("good care cafe") # findall : 일치하는 모든 것을 리스트 형태로 반환
# print(lst)

# 1. p = re.compile("원하는 형태")
# 2. m = p.match("비교할 문자열") : 처음부터 일치하는지 확인
# 3. m = p.search("비교할 문자열") : 주어진 무자열 중에 일치하는게 있는지 확인
# 4. lst = p.findall("비교할 문자열") : 일치하는 모든것을 "리스트" 형태로 반환

# 원하는 형태 : 정규식
# . (ca.e): 하나의 문자를 의미 > care, cafe, case (O) | caffe (X)
# ^ (^de) : 문자열의 시작 > desk, destination (O) | fade (X)
# $ (se$) : 문자열의 끝 > case, base (O) | face (X) 

나도코딩님 영상 참고

728x90
반응형

'Coding > Python' 카테고리의 다른 글

파이썬 리스트 원소 다양한 추가 방법  (0) 2022.03.03
Discord bot with Python #1  (0) 2021.05.27
파이썬 tkinter 1강  (0) 2021.03.09
loading