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
1
  • 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? Commented Jul 18, 2017 at 5:53

3 Answers 3

5

You can try this:

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

Demo

Sign up to request clarification or add additional context in comments.

Comments

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}$

Comments

2

you can simply remove + between your regular express string

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.