正则表达式不允许使用某些特殊字符 [英] Regex not allowing certain special characters

查看:1728
本文介绍了正则表达式不允许使用某些特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下正则表达式,不允许使用某些特殊字符:

I have the following regex which does not allow certain special characters:

if (testString.match(/[`~,.<>;':"\/\[\]\|{}()-=_+]/)){    
    alert("password not valid");
}
else
{
    alert("password valid");
}

这正在工作.如果此正则表达式接受方括号(〜,.<> ;;':: \/\ [\] \ | {}()-= _ ++)中的任何特殊字符,它将接受密码.).

This is working. This regex will accept a password if it does not contain any of the special characters inside the bracket (~,.<>;':"\/\[\]\|{}()-=_+).

我的问题是它也不允许我输入怪异的数字.

My problem here is it also don't allow me to input numbers which is weird.

我在这里错过了什么吗?预先感谢!

Anything I missed here? Thanks in advance!

以下是示例:

jsFiddle

推荐答案

您在那里有一个字符范围:)-= ,其中包括)之间的所有ASCII字符 = (包括数字).将-移至类的末尾或对其进行转义:

You've got a character range in there: )-= which includes all ASCII characters between ) and = (including numbers). Move the - to the end of the class or escape it:

/[`~,.<>;':"\/\[\]\|{}()=_+-]/

此外,您无需转义所有这些字符:

Also, you don't need to escape all of those characters:

/[`~,.<>;':"/[\]|{}()=_+-]/

请注意,在您的情况下,使用 test 代替 match :

Note that in your case, it is probably enough for you, to use test instead of match:

if (/[`~,.<>;':"/[\]|{}()=_+-]/.test(testString))){
    ...

test 返回一个布尔值(这是您所需要的),而 match 返回一个具有所有捕获组的数组(无论如何您都将其丢弃).

test returns a boolean (which is all you need), while match returns an array with all capturing groups (which you are discarding anyway).

请注意,正如达伦·托马斯(Daren Thomas)在评论中指出的那样,您应该决定允许使用哪些字符.因为当前的方法无法处理各种奇怪的Unicode字符,却抱怨一些相当标准的字符,例如 _ .要创建白名单,您只需将字符类和条件都反转:

Note that, as Daren Thomas points out in a comment, you should rather decide which characters you want to allow. Because the current approach doesn't take care of all sorts of weird Unicode characters, while complaining about some fairly standard ones like _. To create a whitelist, you can simply invert both the character class and the condition:

if (!/[^a-zA-Z0-9]/.test(testString)) {
   ...

并包括您要允许的所有字符.

And include all the characters you do want to allow.

这篇关于正则表达式不允许使用某些特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆