5
\$\begingroup\$

I'm learning regex. Here I'm checking a string of type aA1 but want also to check it is only 3 characters long. Is there a better way of doing it please?

str = raw_input("input in form 'aA1' please >")
check = re.compile("[a-z][A-Z][0-9]")
if len(str) == 3:
    validate = check.match(str)
    if validate:
        print "Correct string"
    else:
        print "Incorrect string"
else:
    print "Wrong length"
\$\endgroup\$
1
  • \$\begingroup\$ (Of course there should be 'import re' at the top \$\endgroup\$
    – j-o
    Commented Oct 5, 2014 at 10:55

1 Answer 1

5
\$\begingroup\$

Ref. http://www.regular-expressions.info/anchors.html

Anchors are a different breed. They do not match any character at all. Instead, they match a position before, after, or between characters. They can be used to "anchor" the regex match at a certain position. The caret ^ matches the position before the first character in the string. Applying ^a to abc matches a. ^b does not match abc at all, because the b cannot be matched right after the start of the string, matched by ^. See below for the inside view of the regex engine.

Similarly, $ matches right after the last character in the string. c$ matches c in abc, while a$ does not match at all.

With anchors you may skip length test entirely.

So:

import re
str = raw_input("input in form 'aA1' please >")
check = re.compile("^[a-z][A-Z][0-9]$")
validate = check.match(str)
if validate:
    print "Correct string"
else:
    print "Incorrect string"
\$\endgroup\$
1
  • \$\begingroup\$ In fact a caret isn't needed with re.match at the beginning of the expression in line 3 because .match only matches a pattern occurring at the beginning of a string. re.search would require the opening caret. \$\endgroup\$
    – j-o
    Commented Oct 6, 2014 at 15:25

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.