python-regexHow to match any number with Python regex?
Python regex can be used to match any number. The \d
character class can be used to match any digit from 0 to 9. The +
quantifier can be used to match one or more digits. The following example code block shows how to match any number with Python regex:
import re
pattern = r"\d+"
string = "There are 12 cats and 15 dogs"
match = re.search(pattern, string)
if match:
print(match.group())
The output of the example code is:
12
Code explanation
-
import re
: This imports there
module which provides regular expression matching operations. -
pattern = r"\d+"
: This defines the regular expression pattern which matches one or more digits. -
string = "There are 12 cats and 15 dogs"
: This defines the string which will be searched for matches. -
match = re.search(pattern, string)
: This searches the string for a match to the regular expression pattern. -
if match:
: This checks if a match was found. -
print(match.group())
: This prints the matched text.
Helpful links
More of 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 use word boundaries in Python Regex?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to match a URL path using Python regex?
- How to quote in Python regex?
- How to match one or more occurence in Python regex?
- How to use negative lookbehind in Python regex?
- How to match HTML tags with regex in Python?
See more codes...