我试图使用正则表达式来提取模式内的单词。
我有一些像这样的弦
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 ?
您可以使用组(用'('和')'表示)来捕获字符串的部分内容。匹配对象的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'