您可以使用匹配的組:
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