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 plus sign in Python regex?
- How to match a year with Python Regex?
- How to match a question mark in Python regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to match a UUID using Python regex?
- How to match one or more occurence in Python regex?
- How to replace in a file using Python regex?
- How to remove special characters using Python regex?
See more codes...