sohokai
sohokai

Reputation: 55

issue in detecting 2 consecutive capital letters with python's Regex

Here's the exercise I'm trying to complete:

  1. License plate number A license plate consists of 2 capital letters, a dash ('-'), 3 digits, a dash ('-') and finally 2 capital letters. Write a script to check that an input string is a license plate (input () method). If it's correct, print "good". If it's not correct, print "Not good".

Here is my code:

import re
plate = input("Enter your License plate number:")
patern = '[A-Z]{2}[-]\d{3}[-]\[A-Z]{2}'
if re.match(patern, plate):
    print("good")

else:
    print("NOT good")

Here's my output:

Enter your License plate number:AA-999-AA
NOT good

So I tried with \w instead of [A-Z] and it's working with lowercase letters, but with [A-Z] it doesn't detect capital letters...

I've search on google and on stack overflow, didn't find any solution, could you help me guys?

Thanks a lot!

Upvotes: 4

Views: 935

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50759

You have an obsolete escape character in your regular expression:

\[A-Z]{2} - The \ is not needed as [A-Z] is a character class, you don't want to escape the [ and treat it as a character.

If you remove this you will have:

[A-Z]{2}[-]\d{3}[-]\[A-Z]{2}

Note You can also remove the [] around your -:

[A-Z]{2}-\d{3}-\[A-Z]{2}

Upvotes: 1

Brad Solomon
Brad Solomon

Reputation: 40878

You have an extraneous backslash in the pattern. Just remove it:

pattern = r"[A-Z]{2}-\d{3}-[A-Z]{2}"

Example:

>>> import re
>>> re.match(r"[A-Z]{2}-\d{3}-[A-Z]{2}", "AA-999-AA")
<re.Match object; span=(0, 9), match='AA-999-AA'>

Also, no need to enclose the literal - in a character set [].

Upvotes: 4

Related Questions