Reputation: 55
Here's the exercise I'm trying to complete:
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
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
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