What modifications do I need to make to this RegEx to allow lowercase letters only after a number is in the String?

Viewed 28

I have this RegEx:

^[a-z0-9](?:[a-z0-9]+)*$

How can I modify this so that a lowercase letter can only appear in my string if there is a number and ONLY after that number?

These are expected matches:

AA
AB
1a
1b
1A
1B
A1A
A1a
AB1
AB2
AB1a
AB2b

These would fail:

Aa
Ab
a1
b1
Ab1
a1a
2 Answers

I would use a positive lookbehind to assert that a digit must precede any lowercase letter:

^(?:[A-Z0-9]|(?<=[0-9])[a-z])*$

Demo

As an alternative, a solution without a lookaround could be matching [0-9][a-z] and repeating the outer group 1 or more times to prevent matching an empty string.

^(?:[A-Z0-9]|[0-9][a-z])+$

Explanation

  • ^ Start of string
  • (?: Non capture group
    • [A-Z0-9] Match either A-Z or 0-9
    • | Or
    • [0-9][a-z] Match 0-9 and then a-z
  • )+ Close group and repeat 1+ times to prevent matching an empty string
  • $ End of string

Regex demo

Related