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 count matches with Python regex?
- How to perform a zero length match with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...