How to write a Python Regular Expression to validate numbers?

PythonServer Side ProgrammingProgramming

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


raja
Published on 10-Jan-2018 17:06:12
Advertisements