Reputation: 2021
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?
Upvotes: 1
Views: 1257
Reputation: 626758
You should not quantify lookarounds. They are non-consuming patterns, i.e. 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 stringxyz
- 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));
}
Upvotes: 1
Reputation: 78
/^(xyz34|xyz12)[a-zA-Z0-9]{13}$/
This should work,
Upvotes: 1