0

I am trying to have a regexp to force/validate A string to have both digits (numbers) and alpha chars (a-zA-Z).
doing [a-zA-Z0-9] will allow any combination (including only digits or only letters).
The order has to be random.
I do not know how to force "stuff" in such a case.

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278

1 Answers1

2

You will need to use lookaheads for this. Consider this regex:

^(?=.*[0-9])(?=.*[a-zA-Z])[a-zA-Z0-9]+$

It has 2 lookaheads for forcing presence of digit and alphabet.

(?=.*[0-9])    # assert that there is at least a digit ahead
(?=.*[a-zA-Z]) # assert that there is at least an alphabet ahead
[a-zA-Z0-9]+$  # will match only alphanumerics

Regex Lookaround Reference

Note that if your regex tool/language doesn't support lookaheads then you will have to use alternation:

^[a-zA-Z0-9]*?([0-9][a-zA-Z0-9]*[a-zA-Z]|[a-zA-Z][a-zA-Z0-9]*[0-9])[a-zA-Z0-9]*$
anubhava
  • 761,203
  • 64
  • 569
  • 643