Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for alphanumeric string including at least one digit

Tags:

regex

I'm looking for a regex with at the conditions:

  • a) minimum 13 alphanumeric characters
  • b) maximum 17 alphanumeric characters
  • c) and at least 1 digit.

This regex fulfils a) and b). How can it fulfil also condition c)?

^[a-zA-Z0-9]{13,17}$

Example input texts:

# matching
123456789abcd
123456789abcdef
123456789abcdefg

# no match: too long
123456789abcdefgef

# no match: no digit
abcdefghijklmno

# no match: not alphanumeric only
123456789@abcdefg

The flavor is Java 8.

like image 263
dh762 Avatar asked Mar 02 '23 12:03

dh762


1 Answers

It sounds like you are trying to make a password checker. I suggest that you NOT try to do it all in one single regex.

Check your input against two different regexes that must both match:

^[a-zA-Z0-9]{13,17}$        # 13-17 alphanumerics

and

[0-9]                       # at least one digit

Compared to this suggestion from another answer...

^(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[[:alnum:]]{13,17}$

... it's so much clearer that way, and easier to change when your rules change in the future.

like image 81
Andy Lester Avatar answered Mar 05 '23 16:03

Andy Lester