Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regular expression matching either all uppercase letter and number or just numbers

Tags:

python

regex

import re

re.compile(([0-9]|[A-Z0-9]))

Is this the correct way about doing it?

Thank you!

like image 606
Aaron Phalen Avatar asked Dec 28 '22 03:12

Aaron Phalen


1 Answers

You need to provide re.compile() a string, and your current regular expression will only match a single character, try changing it to the following:

import re

pattern = re.compile(r'^[A-Z\d]+$')

Now you can test strings to see if the match this pattern by using pattern.match(some_string).

Note that I used a raw string literal, which ensures the proper handling of backslashes.

The ^ at the beginning and $ at the end are called anchors, ^ matches only at the beginning of the string and $ matches only at the end of the string, they are necessary since you specified you want to only match strings that are entirely uppercase characters or digits, otherwise you could just match a substring.

like image 152
Andrew Clark Avatar answered May 07 '23 08:05

Andrew Clark