Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to match a string with pythons regex with optional character, but only if that optional character is preceded by another character

I need to match a string that optionally ends with numbers, but only if the numbers aren’t preceded by a 0.

so AAAA should match, AAA1 should, AA20 should, but AA02 should not.

I can figure out the optionality of it, but I’m not sure if python has a "preceded by" or "followed by" flag.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if s.isalnum() and re.match("^[A-Z]+[1-9][0-9]*$", s):
        return True

>Solution :

Try:

^[A-Z]+(?:[1-9][0-9]*)?$

Regex demo.


^[A-Z]+ – match letters from the beginning of string

(?:[1-9][0-9]*)? – optionally match a number that doesn’t start from 0

$ – end of string

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading