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 match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a UUID using Python regex?
- How to replace a certain group using Python regex?
- How to replace all using Python regex?
- How to match zero or one occurence in Python regex?
- How to get all matches from a regex in Python?
- How to match a URL path using Python regex?
- How to remove numbers from a string using Python regex?
See more codes...