Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re for validation string

Tags:

python

regex

Below is code:

import re
string = "02:222222"
if re.match(r'[a-fA-F0-9]+[a-fA-F0-9]+:+[a-fA-F0-9]+[a-fA-F0-9]+$',string):
    print "pass"
else:
    print "fail"

above code is printing "pass"

my expected output should be "fail"

Below are the few examples:

string = 00:20
expected output: pass
string = 00:202
expected ouput: fail
string = 00:2z
expected output: fail
string = 000:2
expected ouput: fail
like image 250
preethy tulpi Avatar asked Dec 24 '22 16:12

preethy tulpi


2 Answers

You can try this:

^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$

Demo

like image 76
Rizwan M.Tuman Avatar answered Jan 09 '23 03:01

Rizwan M.Tuman


Note that + in regexp means "one or more". If you want an exact number of characters (like "XX:XX"), then you should remove the "+"-es:

r'[a-fA-F0-9][a-fA-F0-9]:[a-fA-F0-9][a-fA-F0-9]$'

or, better:

r'([a-fA-F0-9][a-fA-F0-9]):([a-fA-F0-9][a-fA-F0-9])$'

to get the $1 and $2 components of the regexp.

According to this, you can also use:

^[a-fA-F0-9]{2}:[a-fA-F0-9]{2}$

or even more compact:

^[^\W_]{2}:[^\W_]{2}$
like image 25
Laur Ivan Avatar answered Jan 09 '23 03:01

Laur Ivan