我试图使用正则表达式来提取模式内的单词。

我有一些像这样的弦

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(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 (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'

其他回答

也许这更简短,更容易理解:

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'

你可以使用这样的代码:

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')

这里有一种不使用组的方法(Python 3.6或以上):

>>> re.search('2\d\d\d[01]\d[0-3]\d', 'report_20191207.xml')[0]
'20191207'

您需要一个捕获组。

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(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 (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'