【问题标题】:Regex match month name day, year [duplicate]正则表达式匹配月份名称日,年[重复]
【发布时间】:2019-06-01 04:09:52
【问题描述】:

试图从这个字符串中提取日期:

Publisher: Broadway Books; Anniversary, Reprint edition (October 8, 2002)

我想得到这个:October 8, 2002

这是我使用的正则表达式。目标是使其适用于上述格式的任何日期。当我在 https://regex101.com/ 上测试它时它可以工作,但在我的代码中返回“None”。

pattern = re.compile("(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)\s+\d{1,2},\s+\d{4}")
date = pattern.match(tag.get_text())

【问题讨论】:

  • “不起作用”信息量不大。你有什么收获吗?如果是这样,是什么?你确定tag 有应该匹配的文本吗?请提供tag的值,以便我们试用。
  • 一般情况下,您不应该使用match。它没有做你认为它正在做的事情。请改用search。你的固定代码对我有用:pattern.search("foo October 8, 2002 bar").group(0) -> 'October 8, 2002'
  • @cco 在代码中不返回任何内容。我在上面编辑了我的问题

标签: python regex


【解决方案1】:

您正在使用re.match,它会查看文本是否与字符串开头的模式匹配。请改用re.search,它会在字符串中的任何位置查找匹配项。请参阅here 了解更多信息。

代码:

import re

text = "Publisher: Broadway Books; Anniversary, Reprint edition (October 8, 2002)"
pattern = re.compile(
    "(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|Jun(e)?|"
    "Jul(y)?|Aug(ust)?|Sep(tember)?|Oct(ober)?|Nov(ember)?|"
    "Dec(ember)?)\s+\d{1,2},\s+\d{4}")

print(pattern.match(text))  # prints None
print(pattern.search(text))
print(pattern.search(text).group())

结果:

None
<_sre.SRE_Match object; span=(57, 72), match='October 8, 2002'>
October 8, 2002

【讨论】:

  • 谢谢你这对我有用。我现在明白其中的区别了
猜你喜欢
  • 2011-02-08
  • 1970-01-01
  • 2015-12-25
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
相关资源
最近更新 更多