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"
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Oct 5, 2014 at 10:54
\$\endgroup\$
1
  • \$\begingroup\$ (Of course there should be 'import re' at the top \$\endgroup\$ 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"
Mathieu Guindon
75.5k18 gold badges194 silver badges467 bronze badges
answered Oct 5, 2014 at 10:58
\$\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\$ Commented Oct 6, 2014 at 15:25

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.