How to write a Python Regular Expression to validate numbers?


The following code validates a number exactly equal to '2018'

Example

import re
s = '2018'
match = re.match(r'\b2018\b',s)
print match.group()

Output

This gives the output

2018

Example

The following code validates any five digit positive integer

import re
s = '2346'
match = re.match(r'(?<!-)\b[1-9]\d{4}\b',s)
print match
s2 = '56789'
match = re.match(r'(?<!-)\b[1-9]\d{4}\b',s2)
print match.group()

Output

None
56789


Updated on: 20-Feb-2020

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements