Python re for check string

Below is the 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 prints "pass"

my expected result should be "fail"

Below are a 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
+4
source share
3 answers

You can try the following:

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

Demo

+5
source

Note that +in regexp it means "one or more." If you need the exact number of characters (for example, "XX: XX"), you must 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 components $1and $2regular expressions.

Accordingly , you can also use:

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

compact:

^[^\W_]{2}:[^\W_]{2}$
+3

you can just delete +between your regular express line

+ in regular expression means 1 or more of the previous expression

+2
source

Source: https://habr.com/ru/post/1681664/


All Articles