Python/ETC

[python] 간단한 정규식 표현

꼰대 2021. 5. 12. 11:52

ca?e에 해당하는 단어 찾기 (care, cafe, case, cave.....)

 

^ : 문자열의 시작 (^de : desk, destination ...)

. : 하나의 문자 (ca.e : care, cafe, case, cave.....)

$ : 문자열의 끝 (se$ : case, base ...)

 

 

import re

 

 

# . : 하나의 문자를 의미

p = re.compile('ca.e')

 

# case가 위에서 정의한 p와 매치 되기 때문에 case 출력

m = p.match('case')

print(m.group())

 

# caffe는 매치되지 않아서 에러 발생

m = p.match('caffe')

print(m.group())

 

# 매치되지 않을 경우 에러 처리

m = p.match('caffe')

 

if m:

    print(m.group())

else:

    print('매치되지 않음')

 

---------------------------------------------------------------------

import re

 

 

def print_match(m):

    if m:

        # 일치하는 문자열 반환

        print('Group : {0}'.format(m.group()))

        # 입력받은 문자열 출력

        print('String : {0}'.format(m.string))

        # 일치하는 문자열의 시작 index

        print('Start : {0}'.format(m.start()))

        # 일치하는 문자열의 끝 index

        print('End : {0}'.format(m.end()))

        # 일치하는 문자열의 시작과 끝 index

        print('Span : {0}'.format(m.span()))

    else:

        print('매치되지 않음')

 

p = re.compile('ca.e')

 

# 주어진 문자열의 처음부터 일치하는지 확인하기 때문에 careless는 매치됨

m = p.match('careless')

print_match(m)

 

# 주어진 문자열 중에 일치하는게 있는지 확인

m = p.search('good care')

print_match(m)

 

# 일치하는 모든것을 리스트 형태로 반환

lst = p.findall('good care cafe')

print(lst)

반응형