I'm writing a regex that should match the following predicate:
Combination of letters and numbers except number 1.
EG: TRS234, A2B3C4, 2A3B4C, 223GFG
I came up with this regex:
const regex = /^(?:[^1]+[a-z]|[a-z]+[^1])[a-z][^1]*$/i
It matches almost every case except for 2A3B4C
, I've been doing lot of research but I'm not getting why it's not working for that particular case. Any help or suggestions to improve the regex will be greatly appreciated.
Thanks in advance!
Note that [^1]
matches any char but 1
, i.e. it also matches §
, ł
, etc. Also, [a-z][^1]*
matches a letter followed with any 0+ chars other than 1
, so the regex does not validate the expected string pattern.
You may use
const regex = /^(?:[02-9]+[a-z]|[a-z]+[02-9])[a-z02-9]*$/i
Or, a variation:
const regex = /^(?=[a-z02-9]*$)(?:\d+[a-z]|[a-z]+\d)[a-z\d]*$/i
See the regex demo and the regex graph:
Details
^
- start of string(?:[02-9]+[a-z]|[a-z]+[02-9])
- either of the two:
[02-9]+[a-z]
- 1 or more digits other than 1
followed with a letter|
- or[a-z]+[02-9]
- 1 or more letters followed with a digit other than 1
[a-z02-9]*
- 0 or more letters or digits other than 1
$
- end of string.