I need a regex to validate,
I have a pattern like here, '/^(xyz34|xyz12)((?=.*[a-zA-Z])(?=.*[0-9])){13}/g'
But this is allowing whitespace and special characters like ($,% and etc) which is violating the rule #3.
Any suggestion to exclude this whitespace and special characters and to strictly check that it must be letters and numbers?
.*
will match any string, for your requirment you can use this:
/^xyz(34|12)[a-zA-Z0-9]{13}$/g
regex fiddle
/^(xyz34|xyz12)[a-zA-Z0-9]{13}$/
This should work,
You should not quantify lookarounds. They are non-consuming patterns , ie the consecutive positive lookaheads check the presence of their patterns but do not advance the regex index , they check the text at the same position . It makes no sense repeating them 13 times. ^(xyz34|xyz12)((?=.*[a-zA-Z])(?=.*[0-9])){13}
is equal to ^(xyz34|xyz12)(?=.*[a-zA-Z])(?=.*[0-9])
, and means the string can start with xyz34
or xyz12
and then should have at least 1 letter and at least 1 digits.
You may consider fixing the issue by using a consuming pattern like this:
/^(?:xyz34|xyz12)[a-zA-Z\d]{13}$/
or /^xyz(?:34|12)[a-zA-Z0-9]{13}$/
/^xyz(?:34|12)(?=[a-zA-Z]*\d)(?=\d*[a-zA-Z])[a-zA-Z\d]{13}$/
.See the regex demo #1 and the regex demo #2 .
NOTE : these are regex literals, do not use them inside single- or double quotes!
Details
^
- start of string xyz
- a common prefix (?:34|12)
- a non-capturing group matching 34
or 12
(?=[a-zA-Z]*\d)
- there must be at least 1 digit after any 0+ letters to the right of the current location (?=\d*[a-zA-Z])
- there must be at least 1 letter after any 0+ digtis to the right of the current location [a-zA-Z\d]{13}
- 13 letters or digits $
- end of string. JS demo:
var strs = ['xyz34abcdefghijkl1','xyz341bcdefghijklm','xyz34abcdefghijklm','xyz341234567890123','xyz14a234567890123']; var rx = /^xyz(?:34|12)(?=[a-zA-Z]*\d)(?=\d*[a-zA-Z])[a-zA-Z\d]{13}$/; for (var s of strs) { console.log(s, "=>", rx.test(s)); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.