Sunday, 15 April 2012

regex - Regular expression to check string is integer -



regex - Regular expression to check string is integer -

an html form returns me string of number entered user. how utilize regular expressions see if capable of beingness number or not. not want strip away commas , see if can cast int, nor locale.atoi method strings evalaute numbers if nonsense (e.g. locale.atoi('01,0,0') evaluates 100).

nb validation occurs if string contains commas

the re pattern should be:

1st character 1-9 (not zero) 2nd , 3rd characters 0-9 3 digits 1-9 , comma repeated between 0 , 2 times (999,999,999,999 largest number possible in program) 3 digits 1-9

compiled = re.compile("[1-9][0-9]{0,2},(\d\d\d,){0,2}[0-9]{3}")

which not matching end of string correctly, example:

re.match(compiled, '123,456,78')

is matching. have done wrong?

more compact

i suggest more compact:

^[1-9][0-9]{0,2}(?:,[0-9]{3}){0,3}$

see the demo

the ^ asserts @ origin of string [1-9] matches our first digit [0-9]{0,2} matches 2 additional digits (?:,[0-9]{3}) matches comma , 3 digits... between 0 , 3 times $ asserts @ end of string

to validate, do:

if re.search("^[1-9][0-9]{0,2}(?:,[0-9]{3}){0,3}$", subject): # successful match else: # match effort failed

regex python-2.7

No comments:

Post a Comment