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: 2020-02-20T05:45:45+05:30

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements