-2

Can anyone tell how I can write regex for a string that take one or more alphanumeric character followed by an even number of digits?

Valid:

a11a1121
bbbb11a1121

Invalid:

a11a1

I have tried ^[a-zA-Z*20-9]*$ but it is always giving true.

Can you please help in this regard?

Biffen
  • 6,249
  • 6
  • 28
  • 36
Christopher Marlowe
  • 2,098
  • 6
  • 38
  • 68
  • 3
    Possible duplicate of [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – Biffen Nov 12 '18 at 11:52

2 Answers2

1

You can achieve it with this regexp: ^[a-z0-9]*[a-z]+([0-9]{2})*$

Explanation :

  • [a-z0-9]*[a-z]+: a string of at least one character terminated by a non digit one
  • ([0-9]{2})*: an odd sequence of digits (0 or 2*n digits). If the even sequence cannot be null, use ([0-9]{2})+ instead.
Amessihel
  • 5,891
  • 3
  • 16
  • 40
1

The regex that you have mentioned will search for any number of [either a-z, or A-Z or 2 or 0-9]

You can break down your requirement to groups and then handle it accordingly.

Like you require at least one character. so you start with ^([a-zA-Z]+)$

Then you need numbers in the multiple of 2. so you add ^([a-zA-Z]+(\d\d)+)$

Now you need any number of combination of these. So the exp becomes: ^([a-zA-Z]+(\d\d)+)*$

You can use online tools like regex101 for these purpose. The provided regex in action here

suvartheec
  • 3,484
  • 1
  • 17
  • 21