How to extract dates based on months using regex(如何使用正则表达式根据月份提取日期)

import re

pattern = ['[\d]{1,2} [ADFJMNOS]\w* [\d]{2,4}','\d{1,2}/\d{1,2}/\d{2,4}']

text = "He welcomed me on 12 Jan 2014 and there by 15 OF 16 cakes for the party. Next morning on 16/05/2022 he waked up. He attended on 16 Feb 1966"

for i in pattern:
    temp_list = re.findall(i,text)
    print(temp_list)

Required output: 
['12 Jan 2014','16 Feb 1966']
['16/05/2022']

The output is coming with 15 OF 16. Is there any solution to get only the dates with months

Solution:

Reverse the order of findall arguments and ensure correct escaping. (?:) avoids capturing the group.

patterns = [
    r"\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,4}",
    r"\d{1,2}/\d{1,2}/\d{2,4}",
]

for pattern in patterns:
    matches = re.findall(pattern, text)
    print(matches)

Output:

['12 Jan 2014', '16 Feb 1966']
['16/05/2022']
————————
import re

pattern = ['[\d]{1,2} [ADFJMNOS]\w* [\d]{2,4}','\d{1,2}/\d{1,2}/\d{2,4}']

text = "He welcomed me on 12 Jan 2014 and there by 15 OF 16 cakes for the party. Next morning on 16/05/2022 he waked up. He attended on 16 Feb 1966"

for i in pattern:
    temp_list = re.findall(i,text)
    print(temp_list)

Required output: 
['12 Jan 2014','16 Feb 1966']
['16/05/2022']

输出是16个中的15个。有没有什么解决方案可以只获取带有月份的日期

解决方法:

颠倒findall参数的顺序并确保正确转义。(?:)避免捕获该组。

patterns = [
    r"\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,4}",
    r"\d{1,2}/\d{1,2}/\d{2,4}",
]

for pattern in patterns:
    matches = re.findall(pattern, text)
    print(matches)

输出:

['12 Jan 2014', '16 Feb 1966']
['16/05/2022']