HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Regular expressions - match only specified string length

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lengthregularmatchexpressionsstringonlyspecified

Problem

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"

Solution

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"

Code Snippets

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"

Context

StackExchange Code Review Q#64781, answer score: 5

Revisions (0)

No revisions yet.