【问题标题】:Can't get re.search() to work in Python无法让 re.search() 在 Python 中工作
【发布时间】:2015-11-13 18:52:31
【问题描述】:

我有一个类型为“animal cat dog”的字符串,我正在尝试从中提取 animal

this example 之后,我尝试使用 re.search(以及稍后的 re.match),但这并没有产生我预期的结果。 if 语句将通过,但 groups() 将为空。

我的代码:

string = "fox cat dog"
regex = "\S+ cat dog\s*"
m = re.search(regex, string)    
if m:
    temp = m.group(1)

我尝试打印出 m 和 m.groups() ,它们具有以下值:

m: <_sre.SRE_Match object at 0x000000002009A920>  
m.groups(): ()

我通过使用子字符串和 .find() 找到了解决问题的方法,但我很好奇我的原始代码出了什么问题。

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 您的模式中没有定义组。

标签: python regex string-parsing


【解决方案1】:

您只需要在您想要的组中添加一个括号。像这样:

string = "fox cat dog"
regex = "(\S+) cat dog\s*"
#       ~~~~~~Note the parenthesis there
m = re.search(regex, string)    
if m:
    temp = m.group(1)

您可能需要查看documentation 了解更多信息:

(...) 匹配括号内的任何正则表达式, 并指示组的开始和结束;组的内容 可以在执行匹配后检索,并且可以匹配 稍后在带有 \number 特殊序列的字符串中,描述 以下。要匹配文字 '(' 或 ')',请使用 \(\),或将它们括起来 在字符类中:[(] [)]。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2021-07-21
    • 2021-01-25
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    相关资源
    最近更新 更多