您可以使用匹配组:
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'
你组中的其他人。