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
remodule:
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
remodule: 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 float with regex in Python?
- How to match a URL using Python regex?
- How to match a plus sign in 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 match HTML tags with regex in Python?
- How to use word boundaries in Python Regex?
- How to split using Python regex?
- How to use negative lookbehind in Python regex?
- How to ignore case in Python regex?
See more codes...