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.search
my_user_name
re.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
'programing tip' 카테고리의 다른 글
복사 된 웹 텍스트에 추가 정보를 추가하는 방법 (0) | 2020.09.08 |
---|---|
Python 요청 및 영구 세션 (0) | 2020.09.07 |
오류 : 디스플레이를 열 수 없음 : (null) Xclip을 사용하여 SSH 공개 키를 복사 할 때 (0) | 2020.09.07 |
제거가 발생하기 전에 jQuery slideUp (). remove ()가 slideUp 애니메이션을 표시하지 않는 것 같습니다. (0) | 2020.09.07 |
Microsoft.Web.Publishing.Tasks.dll에서 TransformXml 작업을로드 할 수 없습니다. (0) | 2020.09.07 |