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

我有一些像这样的弦

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 ?


当前回答

你可以使用这样的代码:

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

其他回答

你可以使用这样的代码:

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'

您需要从正则表达式中捕获。搜索模式,如果找到,使用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'

您还可以使用捕获组(?P<user>模式)并像字典匹配['user']一样访问组。

string = '''someline abc\n
            someother line\n
            name my_user_name is valid\n
            some more lines\n'''

pattern = r'name (?P<user>.*) is valid'
matches = re.search(pattern, str(string), re.DOTALL)
print(matches['user'])

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