programing tip

Python 추출 패턴 일치

itbloger 2020. 9. 7. 07:53
반응형

Python 추출 패턴 일치


Python 2.7.1 패턴 내에서 단어를 추출하기 위해 Python 정규식을 사용하려고합니다.

다음과 같은 문자열이 있습니다.

someline abc
someother line
name my_user_name is valid
some more lines

"my_user_name"이라는 단어를 추출하고 싶습니다. 나는 뭔가를한다

import re
s = #that big string
p = re.compile("name .* is valid", re.flags)
p.match(s) #this gives me <_sre.SRE_Match object at 0x026B6838>

지금 my_user_name을 어떻게 추출합니까?


정규식에서 캡처해야합니다. search패턴의 경우를 사용하여 문자열을 검색합니다 group(index). 유효한 검사가 수행되었다고 가정합니다.

>>> p = re.compile("name (.*) is valid")
>>> result = p.search(s)
>>> result
<_sre.SRE_Match object at 0x10555e738>
>>> result.group(1)     # group(1) will return the 1st capture.
'my_user_name'

일치 그룹을 사용할 수 있습니다.

p = re.compile('name (.*) is valid')

예 :

>>> import re
>>> p = re.compile('name (.*) is valid')
>>> s = """
... someline abc
... someother line
... name my_user_name is valid
... some more lines"""
>>> p.findall(s)
['my_user_name']

여기서는 모든 인스턴스를 가져 오는 re.findall대신 . 를 사용 하여 일치 개체의 그룹에서 데이터를 가져와야합니다.re.searchmy_user_namere.search

>>> p.search(s)   #gives a match object or None if no match is found
<_sre.SRE_Match object at 0xf5c60>
>>> p.search(s).group() #entire string that matched
'name my_user_name is valid'
>>> p.search(s).group(1) #first group that match in the string that matched
'my_user_name'

주석에서 언급했듯이 정규식을 탐욕스럽지 않게 만들고 싶을 수 있습니다.

p = re.compile('name (.*?) is valid')

to only pick up the stuff between 'name ' and the next ' is valid' (rather than allowing your regex to pick up other ' is valid' in your group.


You could use something like this:

import re
s = #that big string
# the parenthesis create a group with what was matched
# and '\w' matches only alphanumeric charactes
p = re.compile("name +(\w+) +is valid", re.flags)
# use search(), so the match doesn't have to happen 
# at the beginning of "big string"
m = p.search(s)
# search() returns a Match object with information about what was matched
if m:
    name = m.group(1)
else:
    raise Exception('name not found')

You want a capture group.

p = re.compile("name (.*) is valid", re.flags) # parentheses for capture groups
print p.match(s).groups() # This gives you a tuple of your matches.

Maybe that's a bit shorter and easier to understand:

import re
text = '... someline abc... someother line... name my_user_name is valid.. some more lines'
>>> re.search('name (.*) is valid', text).group(1)
'my_user_name'

In Python 3.6+ you can index into a match object instead of using group(), e.g.:

>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match[0]  # the entire match 
'name my_user_name is valid'
>>> match[1]  # the first parenthesized subgroup
'my_user_name'

Here's a way to do it without using groups (Python 3.6 or above):

>>> re.search('2\d\d\d[01]\d[0-3]\d', 'report_20191207.xml')[0]
'20191207'

You can also use a capture group (?P<user>pattern) and access the group like a dictionary match['user'].

string = '''someline abc\n
            someother line\n
            name my_user_name is valid\n
            some more lines\n'''

pattern = r'name (?P<user>.*) is valid'
matches = re.search(pattern, str(string), re.DOTALL)
print(matches['user'])

# my_user_name

참고URL : https://stackoverflow.com/questions/15340582/python-extract-pattern-matches

반응형