1

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.

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

AA3209 should not be match according to the OP. Also, your pattern does not match A000, which, in the absence of more info, should also be a match.
@TimBiegeleisen - you seem to "understand" this much differently than the rest of us.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.