【问题标题】:Python Regex: AttributeError: 'str' object has no attribute 'Match'Python正则表达式:AttributeError:'str'对象没有属性'Match'
【发布时间】:2019-04-04 05:23:56
【问题描述】:

这是我第一次在 python 中使用正则表达式,我试图弄清楚为什么它认为错误“AttributeError: 'str' object has no attribute 'Match'”

我正在 Jupyter 笔记本中执行此操作。我在这里做错了什么?我只看到另一个无用的问题,同样缺少属性错误。

import re
grp =  "Application: Company Name / 184010 - Application Development / 184010 - Contract Express"
rgx = "\w+ *(?!.*-)"
res = grp.match(rgx)
print(res)

【问题讨论】:

  • Wrong syntaxre.match(rgx, grp)re.compile(rgx).match(grp)
  • 你想在这里匹配什么?
  • 最后一个破折号后的所有单词@TimBiegeleisen
  • @meowgoesthedog 谢谢!
  • @TimBiegeleisenweirdly 我没有得到匹配,结果在我使用的正则表达式测试器中还没有匹配。

标签: python regex


【解决方案1】:

您想使用re.match,但它从字符串的开头开始。你可以改用findall

import re
grp =  "Application: Company Name / 184010 - Application Development / 184010 - Contract Express"
rgx = "\w+ *(?!.*-)"
res = re.findall(rgx, grp)
print(res)  # ['Contract ', 'Express']

Python demo

如果后面也不应该有正斜杠,您可以将其与连字符一起添加到字符类中。

请注意,要与单词后面的空格不匹配,您可以从模式中省略 asterix * 后面的空格。

\w+(?!.*[-/])

Regex demo | Python demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2018-12-01
    • 2015-09-30
    • 2021-10-22
    • 2020-09-22
    相关资源
    最近更新 更多