你可能遇到的空间问题
我个人会用\s
或\s+
来代替" "
号空格.这样一来,你
可以匹配所有类型的空格(和换行符).但你可以有更多的限制
并将其替换为horizontal whitespace chars=\h
(在Python中似乎不可用,但等同于
[\t\x{00A0}\x{1680}\x{180E}\x{2000}\x{2001}\x{2002}\x{2003}\x{2004}\x{2005}\x{2006}\x{2007}\x{2008}\x{2009}\x{200A}\x{202F}\x{205F}\x{3000} ]
).这份名单可能会减少.由你来决定是匹配一次还是不止一次.
具有捕获组的正则表达式
因为您可能必须在稍后解析日期,所以让我们捕获这一天,
在一些指定的捕获组中有月份和年份.我建议这样做:
regex = r"""
\b # word boundary
(?: # non-capturing group for the "or"
# Short notation: 14-06-2022, 1-05-23
(?P<short>
(?P<short_day>\d{1,2})
-
(?P<short_month>\d{2})
-
(?P<short_year>\d{2}|\d{4})
)
| # Or
# Text notation: 2 oktober 2023, 31 december 23
(?P<text>
(?P<text_day>\d{1,2}) # day
\s+ # white spaces
(?P<text_month>
januari|februari|maart|april|mei|juni|juli|
augustus|september|oktober|november|december
)
\s+ # white spaces
(?P<text_year>\d{2}|\d{4}) # year with 2 or 4 digits, but not 3.
)
)
\b # word boundary
"""
matches = re.finditer(regex, test_str, re.VERBOSE | re.IGNORECASE)
我使用了这些旗帜:
对于年份,我认为\d{2,4}
不是最好的,因为它将匹配3位数,而不是真正有效的年份值.我把它换成了\d{2}|\d{4}
.
我还在周围添加了单词边界\b
,以避免与
"1-06-123456",可以是产品ID或其他任何东西.
你可以play with this regexCode Generator和
使用Code Generator测试Python代码.