python-regexHow to match digits with Python regex?
Python regex can be used to match digits with the \d character class. This character class matches any single digit from 0 to 9.
For example:
import re
string = '12345'
match = re.search(r'\d', string)
if match:
print(match.group())
Output example
1
The code above uses the re.search() function to search for a single digit in the string 12345. The \d character class is used as the pattern to match. The match.group() function is then used to print the first digit that is matched.
Code explanation
import re: imports theremodule which contains the functions needed for regex operationsstring = '12345': assigns the string12345to the variablestringre.search(r'\d', string): searches for a single digit in the string12345using the\dcharacter class as the patternmatch.group(): prints the first digit that is matched
Helpful links
More of Python Regex
- How to make a case insensitive match with Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to perform a zero length match with Python Regex?
- How to match a year with Python Regex?
- How to match a plus sign in Python regex?
- How to use word boundaries in Python Regex?
- How to replace all using Python regex?
- How to match whitespace in Python regex?
- How to match a URL using Python regex?
- How to get a group from a regex in Python?
See more codes...