-
[python] 파이썬 정규 표현식 (regular expression)코딩 연습/코딩배우기 2020. 9. 27. 21:30
■ 파이썬의 텍스트 내에서 특정한 패턴을 가진 문자(열)을 찾는 경우 사용되는 표현식.
파이썬 re 모듈 사용을 사용하며, 관련 메타문자는 [], () , |, ., *, +, ?, ^, $, \, {} 등이 있음
[] : 모든 문자 () : 그룹화 및 추출패턴지정 | : or 조건식 . : \n(개행)을 제외한 모든 문자와 매칭 * : 0회 이상 + : 1회 이상 ? : 0 or 1 ^ : 문자열 시작(단, [^]의 경우는 제외 의미임) $ : 문자열의 끝 \ : 메타 문자(이스케이프 문자)를 일반문자화 {m,n} : m 이상 n 이하 \d : 숫자 (==[0-9]) \D : 숫자 아닌 것 \s : whitespace(스페이스, 탭, 개행) \S : whitespace 아닌 것 \w : 문자 + 숫자(특수문자 아닌 것. 단, '_'는 포함) \W : 문자 + 숫자 아닌 것
import re string = 'OS는 Windows 10, 64bit이고, memory는 8GB, harddisk는 ssd 512GB 사용' pattern1 = re.compile('\d+') # 컴파일 시 프로그램 속도 향상과 객체 생성으로 인한 재사용성이 좋음) print(type(pattern1)) # <class 're.Pattern'> # 클래스 cnt = 0 for i in dir(pattern1): print(i, end=', ') cnt += 1 if cnt % 5 == 0: print() '''--- 실행 결과 --- __class__, __copy__, __deepcopy__, __delattr__, __dir__, __doc__, __eq__, __format__, __ge__, __getattribute__, __gt__, __hash__, __init__, __init_subclass__, __le__, __lt__, __ne__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__, findall, finditer, flags, fullmatch, groupindex, groups, match, pattern, scanner, search, split, sub, subn, ''' print(pattern1.findall(string)) # ['10', '64', '8', '512'] print(re.findall('\d+', string), len(re.findall('\d+', string))) # 패턴 컴파일 없이 직접 적용 # ['10', '64', '8', '512'] 4 print(re.finditer('\d+', string)) # iterator 객체 생성 # <callable_iterator object at 0x0000027EDFA36670> for i in re.finditer('\d+', string): print(i, i.group()) '''--- 실행 결과 --- <re.Match object; span=(12, 14), match='10'> 10 <re.Match object; span=(16, 18), match='64'> 64 <re.Match object; span=(33, 34), match='8'> 8 <re.Match object; span=(52, 55), match='512'> 512 ''' print(pattern1.match(string)) # None print(pattern1.search(string)) # <re.Match object; span=(12, 14), match='10'> if pattern1.search(string): print(pattern1.search(string).group()) # 10
◎ 리스트 패턴 적용
string = 'OS는 Windows 10, 64bit이고, memory는 8GB, harddisk는 ssd 512GB 사용' string_list = string.split() # 리스트 생성 print(string_list) # ['OS는', 'Windows', '10,', '64bit이고,', 'memory는', '8GB,', # 'harddisk는', 'ssd', '512GB', '사용'] count = 0 string_list2 = [] for lst in string_list: if pattern1.search(lst): string_list2.append(lst) count += 1 print(count, string_list2) # 4 ['10,', '64bit이고,', '8GB,', '512GB'] str1 = 'The quick brown fox jumps over the lazy dog.' str_list = str1.split() pattern = re.compile(r'The', re.I) count = 0 str_list2 = [] for word in str_list: if pattern.search(word): str_list2.append(word) count += 1 print(count, str_list2) # 2 ['The', 'the'] # r'The'에서 r은 Raw String으로 원시(순수)문자임을 나타내는 표기법이다.
◎ 문자열 내 발견된 패턴 출력 - (?P<name>)와 group() 함수 사용
str1 = 'The quick brown fox jumps over the lazy dog.' str_list = str1.split() pattern = re.compile(r'(?P<match_word>The)', re.I) for word in str_list: if pattern.search(word): print(pattern.search(word).group('match_word')) ''' The the '''
(?P<name>)에서 name은 그룹명(변수명과 같은) 의미이고, re.I는 대소문자 미구분 함
◎ 문자열 내 발견된 패턴 문자(열)을 대체하기 - re.sub() 함수 이용
str1 = 'The quick brown fox jumps over the lazy dog.' pattern2 = re.compile(r'The', re.I) print(pattern2.sub('a', str1)) # a quick brown fox jumps over a lazy dog.
[참고] Foundations for Analytics with Python - 파이썬 데이터 분석 입문
'코딩 연습 > 코딩배우기' 카테고리의 다른 글
[python] dict 연습 - 단어(문장)에서 모음 찾기 (0) 2020.10.08 [python] 파이썬에서 환경 변수 읽어오기, 현재 작업 디렉토리 등 (0) 2020.10.08 [python] 파이썬 문자열 관련 함수들 (0) 2020.09.27 [python] 파이썬으로 비밀번호 유효성 검사하는 코딩하기 (0) 2020.09.24 [python] 파이썬 datetime() 함수로 살아온 연월일 계산하기(코딩 연습) (0) 2020.09.23