Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 793
sohokai Avatar asked Oct 19 '25 09:10

sohokai


2 Answers

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 [].

like image 81
Brad Solomon Avatar answered Oct 21 '25 21:10

Brad Solomon


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}
like image 27
Nick Parsons Avatar answered Oct 21 '25 23:10

Nick Parsons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!