我想在使用 javascript regex 时忽略方括号 [英] I want to ignore square brackets when using javascript regex

查看:44
本文介绍了我想在使用 javascript regex 时忽略方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 javascript regex 进行一些数据验证并指定我想要接受的字符(我想接受任何字母数字字符、空格和以下 !&,'\- 和如果需要,我稍后会添加一些).我的代码是:

I am using javascript regex to do some data validation and specify the characters that i want to accept (I want to accept any alphanumeric characters, spaces and the following !&,'\- and maybe a few more that I'll add later if needed). My code is:

var value = userInput;
var pattern = /[^A-z0-9 "!&,'\-]/;
if(patt.test(value) == true) then do something

它工作正常并排除了我不希望用户输入的字母,方括号和插入符号除外.从我读过的所有 javascript 正则表达式教程中,它们都是特殊字符 - 括号表示它们之间的任何字符,在本例中插入符号表示任何不在方括号之间的字符.我在这里和谷歌上搜索过关于为什么这些字符也被接受但找不到解释的解释.

It works fine and excludes the letters that I don't want the user to enter except the square bracket and the caret symbols. From all the javascript regex tutorials that i have read they are special characters - the brackets meaning any character between them and the caret in this instance meaning any character not in between the square brackets. I have searched here and on google for an explanation as to why these characters are also accepted but can't find an explanation.

那么任何人都可以帮忙,为什么我的输入接受方括号和插入符号?

So can anyone help, why does my input accept the square brackets and the caret?

推荐答案

原因是您使用的是 A-z 而不是 A-Za-z.Z (0x5a) 和 a (0x61) 之间的 ascii 范围包括方括号、脱字符、反引号和下划线.

The reason is that you are using A-z rather than A-Za-z. The ascii range between Z (0x5a) and a (0x61) includes the square brackets, the caret, backquote, and underscore.

这篇关于我想在使用 javascript regex 时忽略方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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