Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading