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 replace a certain group using Python regex?
- How to perform a zero length match with Python Regex?
- How to match whitespace in Python regex?
- How to match HTML tags with regex in Python?
- How to replace in a file using Python regex?
- How to regex match excluding a word in Python?
- How to use word boundaries in Python Regex?
- How to get a group from a regex in Python?
- How to match a year with Python Regex?
- How to match a UUID using Python regex?
See more codes...