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 there
module which contains the functions needed for regex operationsstring = '12345'
: assigns the string12345
to the variablestring
re.search(r'\d', string)
: searches for a single digit in the string12345
using the\d
character class as the patternmatch.group()
: prints the first digit that is matched
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a UUID using Python regex?
- How to match a year with Python Regex?
- How to replace all using Python regex?
- How to use word boundaries in Python Regex?
- How to remove numbers from a string using Python regex?
- How to get a group from a regex in Python?
- How to match a URL path using Python regex?
- How to use quantifiers in Python regex?
- How to quote in Python regex?
See more codes...