YUYANE

Python / Regular Expression(Regex) 본문

Programming Languages/PYTHON

Python / Regular Expression(Regex)

YUYA 2021. 1. 13. 13:13

Regular Expression

검색 패턴을 정의하는 일련의 문자열

 

 

1. re.search()

 

  원하는 정보를 찾을 때 사용

import re

patterns = ['term1','term2']

text = 'This is a string with term1, but not the other!'

for pattern in patterns:
    print("I'm searching for: "+pattern)

    if re.search(pattern, text):
        print("Match!")
    else:
        print("No match!")

  결과:

  I'm Searching for: term1  

  Match!

  I'm searching for: term2 

  No match!

 

  re.search. 메서드의 결과 값은 어떤 유형일까?

patterns = ['term1','term2']

text = 'This is a string with term1, but not the other!'

match = re.search('term1', text)
print(type(match))
print(match.start())

  결과 : 

  <class 're.Match'>

  22

 

  따라서 변수 match는 re.Match에 속해있는 메서드들을 사용할 수 있다.

  예를 들어 match.start( )

 

 

2. re.split()

 

  특정 문자를 기준으로 split도 가능하다.

split_term = '@'
email = 'user@gmail.com'
print(re.split(split_term,email))

  결과:

  [ 'user', 'gmail.com' ]

 

 

3. re.findall()

 

  첫 번째 인자와 매치되는 것들을 리스트로 반환한다.

re.findall('match','test phrase match is in middle')

  결과:

  [ 'match' ]

 

  # Repetition Syntax

 

    조금 응용해서 아래와 같은 메서드를 만들어보자.

def multi_re_find(patterns,phrase):
    '''
    Takes in a list of regex patterns
    Prints a list of all matches
    '''
    for pattern in patterns:
        print 'Searching the phrase using the re check: %r' %pattern
        print re.findall(pattern,phrase)
        print '\n'
        
test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'


        

 

    두 번째 인자 phrase 자리에는 test_phrase를 넣을 것이다.

    patterns 자리에 어떤 변수가 들어가느냐에 따라 반환할 리스트에 차이를 줄 수 있다.

 

test_patterns = [ 'sd*',     # s followed by zero or more d's
                'sd+',          # s followed by one or more d's
                'sd?',          # s followed by zero or one d's
                'sd{3}',        # s followed by three d's
                'sd{2,3}',      # s followed by two to three d's
                ]

 

    예를 들어 test_patterns = ['sd+'] 를 보자.

    주석의 설명대로 s 뒤에 1개 혹은 그 이상의 d가 붙는 요소들의 리스트를 반환할 것이다.

    [ 'sd' , 'sd' , 'sddd' , 'sddd' , 'sddd', 'sdddd' ]

 

  #Character Sets

 

    입력값에서 특정 문자를 찾고 싶을 때 사용

    []와 함께 사용한다.

test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'

test_patterns = [ '[sd]',    # either s or d
            's[sd]+']   # s followed by one or more s or d


multi_re_find(test_patterns,test_phrase)

 

    예를 들어 test_patterns = [ 's[sd]+' ]를 보자.

    s 뒤에 1개 혹은 그 이상의 s나 d를 가진 것들의 리스트를 반환한다.

    [ 'sdsd', 'sssddd', 'sdddsddd', 'sds', 'sssss', 'sdddd' ]

 

  #Exclusion

 

    특정 요소를 제외하고 싶을 때, []에 ^을 사용하면 된다.

test_phrase = 'This is a string! But it has punctuation. How can we remove it?'
re.findall('[^!.? ]+',test_phrase)

    결과 : [ 'This is a string' , 'But it has punctuation' , 'How can we remove it' ]

 

 

  #Ranges

 

    찾고 싶은 범위를 지정해줄 수도 있다.

test_phrase = 'This is an example sentence. Lets see if we can find some letters.'

test_patterns=[ '[a-z]+',      # sequences of lower case letters
                '[A-Z]+',      # sequences of upper case letters
                '[a-zA-Z]+',   # sequences of lower or upper case letters
                '[A-Z][a-z]+'] # one upper case letter followed by lower case letters

multi_re_find(test_patterns,test_phrase)

    예를 들어 test_patterns = [ '[A_Z]+' ] 라면,

    결과: [ 'T' , 'L' ]

 

  #Escape Codes

 

    숫자, 숫자가 아닌 문자, 빈칸 등의 데이터에서 어떤 패턴을 찾고싶다면 'r'을 사용할 수 있다.

test_phrase = 'This is a string with some numbers 1233 and a symbol #hashtag'

test_patterns=[ r'\d+', # sequence of digits
                r'\D+', # sequence of non-digits
                r'\s+', # sequence of whitespace
                r'\S+', # sequence of non-whitespace
                r'\w+', # alphanumeric characters
                r'\W+', # non-alphanumeric
                ]

multi_re_find(test_patterns,test_phrase)

    예를 들어 test_patterns = [ r'\d+' ] 라면,

    결과 : [ '1233' ]

 

 

 

 

 

 

 

아래에서 더 많은 Regular Expressions들을 찾아 볼 수 있다.

en.wikipedia.org/wiki/Regular_expression

 

 

 

출처

www.udemy.com/course/python-and-django-full-stack-web-developer-bootcamp/learn/lecture/6605080#announcements

 

 

Comments