4

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
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
preethy tulpi
  • 415
  • 1
  • 5
  • 15
  • What exactly do you expect to match? Explain the structure of the matching input. Your example is too narrow. Is it two digits followed by colon followed by two digits? – DYZ Jul 18 '17 at 05:53

3 Answers3

5

You can try this:

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

Demo

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
3

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}$
Laur Ivan
  • 4,117
  • 3
  • 38
  • 62
2

you can simply remove + between your regular express string

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

Ebrahim Poursadeqi
  • 1,776
  • 2
  • 17
  • 27