Python提取模式匹配

2024-04-20 11:34:54 发布

您现在位置:Python中文网/ 问答频道 /正文

Python2.7.1 我试图使用python正则表达式来提取模式中的单词

我有一些像这样的绳子

someline abc
someother line
name my_user_name is valid
some more lines

我想提取“我的用户名”这个词。我做了一些像

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>

如何提取我的用户名?


Tags: namereismyline模式some单词
3条回答

您可以使用匹配的组:

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,您需要从match对象上的组获取数据:

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

如注释中所述,您可能希望使regex不贪婪:

p = re.compile('name (.*?) is valid')

只在'name '和下一个' is valid'之间提取内容(而不是允许regex提取组中的其他' is valid')。

你可以用这样的东西:

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

你需要从regex中捕获。search对于模式,如果找到,则使用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.
'my_user_name'

相关问题 更多 >