find dates in a string using regex in python

To find dates in a string using regex in Python, we can use the re module which provides support for regular expressions. We need to specify a pattern that matches the format of the date we're searching for.

Here is an example code block that uses regex to find dates in a string:

main.py
import re

# Sample string
string_with_dates = "The event will take place on 2022-05-20 and 2022/05/22"

# Regex pattern to match dates in yyyy-mm-dd or yyyy/mm/dd format
date_pattern = r"\d{4}[-/]\d{2}[-/]\d{2}"

# Find all the matches
dates = re.findall(date_pattern, string_with_dates)

# Print the dates
print(dates)
321 chars
14 lines

Output:

main.py
['2022-05-20', '2022/05/22']
29 chars
2 lines

In the above example, we define a regex pattern r"\d{4}[-/]\d{2}[-/]\d{2}" that matches any four digits followed by a hyphen or forward slash, followed by two digits, another hyphen or forward slash, and finally two more digits.

We then use re.findall() method to extract all the matches from our sample string. The method returns a list of all the matched patterns.

Finally, we print the dates found in our string with the help of print() function.

gistlibby LogSnag