ABOUT ME

-

  • [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 : 문자 + 숫자 아닌 것

    good4me.co.kr

    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 - 파이썬 데이터 분석 입문

     

Designed by goodthings4me.