Python 提取模式匹配

新手上路,请多包涵

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

我有一些看起来像这样的字符串

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

原文由 Kannan Ekanath 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 245
2 个回答

您需要从正则表达式中捕获。 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 (stuff within the brackets).
                        # group(0) will returned the entire matched text.
'my_user_name'

原文由 UltraInstinct 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用匹配组:

 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'

原文由 mgilson 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题