python-regexHow to match a year with Python Regex?
Python Regex can be used to match a year with the following steps:
- Create a regular expression pattern to match a year using the
re
module:
import re
year_pattern = re.compile(r'\d{4}')
- Use the
findall()
method to search for the pattern in a string:
year_matches = year_pattern.findall('The year is 2020')
- The
findall()
method will return a list of matches:
print(year_matches)
['2020']
Code explanation
re
module: used to create regular expression patternscompile()
method: used to compile a regular expression patternfindall()
method: used to search for the pattern in a string
Helpful links
More of Python Regex
- How to replace all using Python regex?
- How to get all matches from a regex in Python?
- How to match a YYYY-MM-DD date with Python Regex?
- How to get a group from a regex in Python?
- How to match a UUID using Python regex?
- How to ignore case in Python regex?
- How to get a number from a string with regex in Python?
- How to match whitespace in Python regex?
- How to validate an IP using Python regex?
See more codes...