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.
Asked
Active
Viewed 77 times
0

Itay Moav -Malimovka
- 52,579
- 61
- 190
- 278
1 Answers
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
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
-
Note this will allow also &&password1, While I want to force only letters and numbers. – Itay Moav -Malimovka Sep 28 '16 at 18:03
-
Oh ok in that case let me update the regex – anubhava Sep 28 '16 at 18:09
-
Using what anubhava posted, does this work? `^([0-9]?[a-zA-Z]|[a-zA-Z]?[0-9])[\w\d]*$` – sdexp Sep 28 '16 at 18:12