for match in re.finditer(
r"""(?ix) # case-insensitive, verbose regex
\b # match a word boundary
(?: # match the following three times:
(?: # either
\d+ # a number,
(?:\.|st|nd|rd|th)* # followed by a dot, st, nd, rd, or th (optional)
| # or a month name
(?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*)
)
[\s./-]* # followed by a date separator or whitespace (optional)
){3} # do this three times
\b # and end at a word boundary.""",
subject):
# match start: match.start()
# match end (exclusive): match.end()
# matched text: match.group()
它绝对不是完美的,并且容易错过一些日期(特别是如果它们不是英语的-21. Mai 2006将失败,以及4ème décembre 1999),并且匹配像August Augst Aug这样的无意义内容,但是由于在示例中几乎所有内容都是可选的,所以在regex级别上没有什么可以做的。在
下一步是将所有匹配项输入到解析器中,看它是否能够将它们解析为一个合理的日期。在
正则表达式无法正确解释上下文。想象一个(愚蠢的)文本,比如You'll find it in box 21. August 3rd will be the shipping date.,它将匹配21. August 3rd,当然这是无法解析的。在
这将查找示例语句中的所有日期:
它绝对不是完美的,并且容易错过一些日期(特别是如果它们不是英语的-
21. Mai 2006
将失败,以及4ème décembre 1999
),并且匹配像August Augst Aug
这样的无意义内容,但是由于在示例中几乎所有内容都是可选的,所以在regex级别上没有什么可以做的。在下一步是将所有匹配项输入到解析器中,看它是否能够将它们解析为一个合理的日期。在
正则表达式无法正确解释上下文。想象一个(愚蠢的)文本,比如
You'll find it in box 21. August 3rd will be the shipping date.
,它将匹配21. August 3rd
,当然这是无法解析的。在如果您想在较长的文本中找到这些日期,那么尝试搜索数字和月份组,并将它们提供给这个解析器。如果文本看起来不像日期,则会引发异常。在
^{pr2}$相关问题 更多 >
编程相关推荐