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.
# group(0) will returned the entire matched text.
'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')
정규식이 그룹의 다른 항목을 선택하도록 허용하지 않고 'name '
다음 사이의 항목 만 선택합니다 .' is valid'
' is valid'
답변
다음과 같이 사용할 수 있습니다.
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')
답변
아마도 조금 더 짧고 이해하기 쉽습니다.
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'
답변
캡처 그룹을 원합니다 .
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.
답변
그룹 ( '('
및로 ')'
표시됨)을 사용하여 문자열의 일부를 캡처 할 수 있습니다 . group()
그런 다음 일치 개체의 메서드가 그룹의 콘텐츠를 제공합니다.
>>> import re
>>> s = 'name my_user_name is valid'
>>> match = re.search('name (.*) is valid', s)
>>> match.group(0) # the entire match
'name my_user_name is valid'
>>> match.group(1) # the first parenthesized subgroup
'my_user_name'
Python 3.6 이상에서는 다음 을 사용하는 대신 일치 객체로 인덱싱 할 수도 있습니다 group()
.
>>> match[0] # the entire match
'name my_user_name is valid'
>>> match[1] # the first parenthesized subgroup
'my_user_name'
답변
다음은 그룹을 사용하지 않고 수행하는 방법입니다 (Python 3.6 이상).
>>> re.search('2\d\d\d[01]\d[0-3]\d', 'report_20191207.xml')[0]
'20191207'
