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