您可以使用匹配的组:
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'
。
工作你确定这不是第一场比赛的“组(0)”吗? – sharshofski 2015-04-16 14:04:34
有点迟了,但是有,也没有。 'group(0)'返回匹配的文本,而不是第一个捕获组。代码评论是正确的,而你似乎混淆捕获组和匹配。 'group(1)'返回第一个捕获组。 – andrewgu 2015-08-07 01:31:48