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.py321 chars14 lines
Output:
main.py29 chars2 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