I have a requirement where there is a customet name text box and the user able to input customer name to search customer. And the condition is user can add do wild card search putting * either infront or after the customer name. And the customer name should be minimum three characters long. I am using Regex to validate the user entry. Now in case the input is like "*aaa*" .. I am validate this type of input using the following regex :
[*]{1}([az]|[AZ]|[0-9]){3,}[*]{1}
The code is like below:
var str = "*aaa*"; var patt = new RegExp("[*]{1}([az]|[AZ]|[0-9]){3,}[*]{1}"); var res = patt.test(str); alert(res);
var str = "*aaa***"; var patt = new RegExp("[*]{1}([az]|[AZ]|[0-9]){3,}[*]{1}"); var res = patt.test(str); alert(res);
var str = "*aaa*$$$$"; var patt = new RegExp("[*]{1}([az]|[AZ]|[0-9]){3,}[*]{1}"); var res = patt.test(str); alert(res);
Now for the input "*aaa*" res is coming true. But for this type of inputs also "*aaa**", "*aaa*$" its comimg true. And this expected as these expressions also contains the part( *aaa*) which satisfies the regex.But these inputs("*aaa**", *aaa*$** etc. ) are wrong.
Please let me know where I am doing wrong ? is there any issue with the regex or the way checking is wrong ?
^(?:[*]([a-z]|[A-Z]|[0-9]){3,}[*])$
Use anchors ^$
to disable partial matching.See demo.
The string *aaa*$$$
contains a segment of *aaa*
, so it will yield true
; to match against the whole string you need to add anchors on both sides. The $
and ^
anchors assert the start and end of the subject respectively.
Also, you can simply the expression greatly by using a character class trick. The \\w
is comprised of [0-9a-zA-Z_]
, and we only don't want the underscore, so we can use a negative character class with the opposite of \\w
(which is \\W
) and an underscore; I agree, it takes some mental power ;-)
var str = "*aaa*$"; var patt = /^\\*[^\\W_]{3,}\\*$/; var res = patt.test(str); alert(res); // false
Alternatively, you can merge all your character classes together into one like so:
[A-Za-z0-9]
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.