简体   繁体   English

javascript-正则表达式字母数字和特殊字符

[英]javascript- regular expression alphanumeric and special characters

I am trying to allow alphanumeric and some special characters 我正在尝试允许字母数字和一些特殊字符

var regx = /^[A-Za-z0-9._-\] ]+$/;

I tried escaping the ] sign with the forward slash but it still doesnt work. 我尝试用正斜杠转义]符号,但仍然无法正常工作。 What am I missing 我在想什么

You also need to escape the - character: 您还需要转义-字符:

/^[A-Za-z0-9._\-\] ]+$/
//------------^

Escaping - is not always necessary. 转义-并非总是必要的。 Here, however, it is used inside square brackets which makes the JavaScript engine assume that you are trying to specify the range from _-] which causes a "Range out of order in character class" error. 但是,这里在方括号内使用它,这使JavaScript引擎假定您正在尝试指定_-]的范围,这会导致“字符类的范围乱序”错误。

Note that /[_-a]/ is valid regex and matches characters _ , ` and a (ASCII codes 95...97); 注意/[_-a]/是有效的正则表达式,并且匹配字符_`a (ASCII码95 ... 97); which may not be the desired outcome. 这可能不是理想的结果。

If you try your regex on an online regex tester like regex101 you'd get the error: 如果您在像regex101这样的在线正则表达式测试仪上尝试正则表达式,则会收到错误消息:

Regex link 正则表达式链接

在此处输入图片说明

You have to escape - using \\- : 您必须逃脱-使用\\-

^[A-Za-z0-9._\-\] ]+$

Btw, you can shorten your regex to: 顺便说一句,您可以将正则表达式缩短为:

^[\w.\-% ]+$

Edit: added regex for your comment: 编辑:为您的评论添加了正则表达式:

^[\w.-\]\[ #$>()@{}'"]+$

Working demo 工作演示

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

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