python-regexHow to match certain amount of digits with Python regex?
Python regex can be used to match certain amount of digits. The \d
character class is used to match any single digit. To match a specific amount of digits, the {n}
quantifier can be used, where n
is the number of digits to match. For example, to match exactly 5 digits, the regex \d{5}
can be used.
import re
# Match exactly 5 digits
pattern = r"\d{5}"
# Test string
test_string = "1234567890"
# Match the pattern
result = re.match(pattern, test_string)
# Print the result
print(result)
Output example
<re.Match object; span=(0, 5), match='12345'>
Code explanation
\d
: character class used to match any single digit{n}
: quantifier used to match a specific amount of digits, wheren
is the number of digits to match
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to replace all using Python regex?
- How to match a question mark in Python regex?
- How to ignore case in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to count matches with Python regex?
- How to make a case insensitive match with Python regex?
- How to perform a zero length match with Python Regex?
- How to match a year with Python Regex?
See more codes...