简体   繁体   English

验证需要匹配特定条件的字符串(正则表达式)?

[英]Validate the string which needs to match particular condition(Regular Expression)?

I want to validate the string, which should not contain any special characters except underscore(_). 我要验证的字符串,除了下划线(_)之外,不应包含任何特殊字符。 For that i have written below code but i was not able to get it through. 为此,我编写了以下代码,但无法通过它。

var string = 'pro$12';
var result = /[a-zA-Z0-9_]*/.test(string);

In the above the given string is not valid but i got the result as a true. 在上面给定的字符串是无效的,但我得到的结果为true。 Can any body tell what i am doing wrong here? 有人能告诉我我在做什么错吗?

It returns true because, it is able to match pro . 它返回true因为它能够匹配pro You can see the actual matched string, with the match function, like this. 您可以使用match函数查看实际匹配的字符串,如下所示。

console.log(string.match(/[a-zA-Z0-9_]*/));
# [ 'pro', index: 0, input: 'pro$12' ]

Even when it doesn't match anything, for example, your input is '$12', then also it will return true . 即使它与任何内容都不匹配,例如,您的输入为'$ 12',它也会返回true Because, * matches 0 or more characters. 因为*匹配0个或更多字符。 So, it matches zero characters before $ in $12 . 因此,它匹配之前零个字符$$12 (Thanks @Jack for pointing out ) (感谢@Jack指出

So, what you actually need is 所以,您真正需要的是

console.log(/^[a-zA-Z0-9_]*$/.test(string));
# false

^ means beginning of the string and $ means ending of the string. ^表示字符串的开头, $表示字符串的结尾。 Basically you are telling the RegEx engine that, match a string which has only the characters from the character class, from the beginning and ending of the string. 基本上,您是在告诉RegEx引擎,从字符串的开头和结尾匹配一个仅包含字符类中字符的字符串。

Note: Instead of using the explicit character class, [a-zA-Z0-9_] , you can simply use \\w . 注意:您可以简单地使用\\w来代替使用显式字符类[a-zA-Z0-9_] It is exactly the same as the character class you mentioned. 它与您提到的字符类完全相同。

Quoting from MDN Docs for RegExp, 引用MDN文档中的RegExp,

\\w \\ W

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. 匹配基本拉丁字母中的任何字母数字字符,包括下划线。 Equivalent to [A-Za-z0-9_] . 等效于[A-Za-z0-9_]

For example, /\\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D." 例如, /\\w/匹配'a'"apple," '5'"$5.28,"'3'中的"3D."

So, your RegEx can be shortened like this 因此,您的RegEx可以像这样缩短

console.log(/^\w*$/.test(string));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM