我正在嘗試捕獲可以在這樣的字串中的日期
'2022 年 1 月 30 日、4 月 6 日和 10 月 12 日'
我正在使用 python 正則運算式模塊(它與 re 相同,但具有“重疊”選項)。我需要將最終結果作為此串列
['2022 年 1 月 30 日'、'2022 年 4 月 6 日'、'2022 年 10 月 12 日']
到目前為止,這個運算式
regex.findall(r'(?:\d\d | \d )(?:jan|feb|mar|ap|may|jun|jul|aug|sep|oct|nov|dec)(?:.*)20(?:\d\d)', d, overlapped=True)
我正進入(狀態
['2022 年 1 月 30 日和 4 月 6 日和 10 月 12 日','2022 年 4 月 6 日和 10 月 12 日','2022 年 10 月 12 日']
提前致謝。
uj5u.com熱心網友回復:
您可以使用串列理解和 2 個捕獲組:
\b(\d (?:jan|feb|mar|ap|may|jun|jul|aug|sep|oct|nov|dec))(?=.*\b(20\d\d))\b
請參閱正則運算式演示和Python 演示。
import re
pattern = r"\b(\d (?:jan|feb|mar|ap|may|jun|jul|aug|sep|oct|nov|dec))(?=.*\b(20\d\d))\b"
s = r"30 jan and 6 apr and 12 oct 2022"
res = [' '.join(s) for s in re.findall(pattern, s)]
print(res)
輸出
['30 jan 2022', '6 ap 2022', '12 oct 2022']
請注意,(?:.*)不需要(?:\d\d)非捕獲組,因為組本身在模式中沒有任何用途。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476496.html
上一篇:用戶只能看到他的資料Django
