简体   繁体   中英

Need regex for a string having characters followed by even number of digits

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?

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

Explanation :

  • [a-z0-9]*[az]+ : 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.

The regex that you have mentioned will search for any number of [either az, or AZ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM