不允许使用除允许字符之外的特殊字符 javascript regex
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18396534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Do not allow special characters except the allowed characters javascript regex
提问by Gerald
I have the following javascript code for my password strength indicator:
我的密码强度指示器有以下 javascript 代码:
if (password.match(/([!,@,#,$,%])/)
{
strength += 2
}
So what this do is if the password contains one of these allowed characters (!,@,#,$,%), it will add a value to the strength of indicator.
因此,如果密码包含这些允许的字符之一 (!,@,#,$,%),它将为指标的强度增加一个值。
My problem is I also want to decrease the strength of the password indicator once other special characters are present on the password. For example: ^,`,~,<,>
我的问题是,一旦密码中出现其他特殊字符,我还想降低密码指示符的强度。例如:^,`,~,<,>
To remove confusion, basically I don't want any other special characters except the ones that is present above (!,@,#,$,%). So I did it hard coded, writing all special characters that I don't want.
为了消除混淆,基本上我不想要任何其他特殊字符,除了上面出现的那些 (!,@,#,$,%)。所以我做了硬编码,写了所有我不想要的特殊字符。
I tried using this:
我尝试使用这个:
if (password.match(/([^,`,~,<,>])/)
{
strength -= 2
}
But I also don't want to include ", 'and ,but then if I include them on my if condition, it will throw me an error saying syntax error on regular expression. I understand this because i know "represents a string which must be closed. Can I do something about it? Thanks in advance!
但是我也不想有",'和,后来如果我包括他们对我的if条件,就会把我一个错误说正则表达式的语法错误。我理解这一点,因为我知道"代表一个必须关闭的字符串。我可以做些什么吗?提前致谢!
回答by Hashbrown
You don't need to separate your individual characters by commas, nor do you need to wrap the only term in brackets.
您不需要用逗号分隔各个字符,也不需要将唯一的术语括在方括号中。
This should work:
这应该有效:
/[`^~<>,"']/
note the carat (^is not at the front, this has a special meaning when placed at the start of the []block)
注意克拉(^不是在前面,这在[]块的开头有特殊的含义)
Also you should use test()because you only want a boolean if-contains result
你也应该使用,test()因为你只想要一个布尔值 if-contains 结果
/[`^~<>,"']/.test(password)
回答by Emil Stolarsky
What you want to do is escape each of ", ', and ,using a \. The regex you're looking for is:
您想要做的是转义每个", ',并,使用\. 您正在寻找的正则表达式是:
/([\^\`\~\<\,\>\"\'])/
I actually generated that using the JSVerbalExpressionslibrary. I highly recommend you check it out! To show you how awesome it is, the code to generate the above regex is:
我实际上是使用JSVerbalExpressions库生成的。我强烈建议你检查一下!为了向您展示它有多棒,生成上述正则表达式的代码是:
var tester = VerEx()
.anyOf("^,`'\"~<>");
console.log(tester); // /([\^\`\~\<\,\>\"\'])/
回答by Vandesh
Include these special characters in square brackets without commas and see if it works.
将这些特殊字符包含在没有逗号的方括号中,看看它是否有效。
You can try it out here - http://jsfiddle.net/BCn7h/
你可以在这里尝试 - http://jsfiddle.net/BCn7h/
Eg :
例如:
if (password.match(/["',]/)
{
strength -= 2
}

