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 match a question mark in Python regex?
- How to use word boundaries in Python Regex?
- How to get all matches from a regex in Python?
- How to match a UUID using Python regex?
- How to replace a certain group using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to validate an IP using Python regex?
- How to use quantifiers in Python regex?
- How to use negative lookbehind in Python regex?
- How to match a URL using Python regex?
See more codes...