"AND" is not really possible in regexes. You have to use advanced tricks such as positive lookaheads.
/^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{3,10}\z/
Of course, you could possibly use multiple regexs for increased readability.
/^[A-Za-z0-9]{3,10}\z/ && /[A-Za-z]/ && /[0-9]/
Update: For fun,
Eliminates one lookahead:
/^(?=[A-Za-z0-9]{3,10}\z).*(?:[0-9][A-Za-z]|[A-Za-z][0-9])/
Eliminates both lookahead:
/(?>(?:[0-9][A-Za-z]|[A-Za-z][0-9]).*\z)(?(?{pos()<3||pos()>10})(?!))/
All tested.
Update: Benchmarked. (Benchmarking Code, a prime example of a good Benchmark if you ask me.)
----------------------------------------
Short (arg: 2j)
Rate ikegami4 ikegami3 ikegami2 ikegami1
ikegami4 573/ms -- -60% -76% -77%
ikegami3 1428/ms 149% -- -40% -44%
ikegami2 2392/ms 318% 68% -- -5%
ikegami1 2529/ms 342% 77% 6% --
----------------------------------------
Fine (arg: n4a1z9)
Rate ikegami4 ikegami2 ikegami1 ikegami3
ikegami4 638/ms -- -11% -18% -20%
ikegami2 715/ms 12% -- -8% -10%
ikegami1 776/ms 22% 9% -- -2%
ikegami3 794/ms 24% 11% 2% --
----------------------------------------
Just Letters (arg: nhfdmzaa)
Rate ikegami4 ikegami3 ikegami2 ikegami1
ikegami4 397/ms -- -16% -44% -45%
ikegami3 471/ms 19% -- -34% -35%
ikegami2 714/ms 80% 52% -- -2%
ikegami1 728/ms 83% 55% 2% --
----------------------------------------
Long (arg: qq3m3aaaazz3)
Rate ikegami4 ikegami1 ikegami3 ikegami2
ikegami4 157/ms -- -79% -88% -89%
ikegami1 746/ms 376% -- -45% -45%
ikegami3 1351/ms 762% 81% -- -1%
ikegami2 1365/ms 770% 83% 1% --
My first choice based solely on benchmarks would be ikegami2 (the three regexps).
My first choice based solely on benchmarks would be ikegami1 (straightforward lookahead).
|