简体   繁体   English

限制特殊字符的正则表达式

[英]Regular Expression to restrict special characters

i have an address field in my form and i want to restrict我的表单中有一个地址字段,我想限制
* | \\ " : < > [ ] { } \\ ( ) '' ; @ & $
i have tried with我试过

var nospecial=/^[^* | \ " : < > [ ] { } ` \ ( ) '' ; @ & $]+$/;
            if(address.match(nospecial)){
                alert('Special characters like * | \ " : < > [ ] { } ` \ ( ) \'\' ; @ & $ are not allowed');
                return false;

but it is not working.但它不起作用。 Please tell me what i missed?请告诉我我错过了什么?

You need to escape the closing bracket (as well as the backslash) inside your character class.您需要转义字符类中的结束括号(以及反斜杠)。 You also don't need all the spaces:您也不需要所有空格:

var nospecial=/^[^*|\":<>[\]{}`\\()';@&$]+$/;

I got rid of all your spaces;我摆脱了你所有的空间; if you want to restrict the space character as well, add one space back in.如果您还想限制空格字符,请重新添加一个空格。

EDIT As @fab points out in a comment, it would be more efficient to reverse the sense of the regex:编辑正如@fab 在评论中指出的那样,反转正则表达式的意义会更有效:

var specials=/[*|\":<>[\]{}`\\()';@&$]/;

and test for the presence of a special character (rather than the absence of one):并测试是否存在特殊字符(而不是不存在):

if (specials.test(address)) { /* bad address */ }

/[$&+,:;=?[]@#|{}'<>.^*()%!-/]/ /[$&+,:;=?[]@#|{}'<>.^*()%!-/]/

below one shouldn't allow to enter these character and it will return blank space下面一个不应该允许输入这些字符,它会返回空格

.replace(/[$&+,:;=?[\]@#|{}'<>.^*()%!-/]/,"");

Use the below function使用以下功能

function checkSpcialChar(event){
    if(!((event.keyCode >= 65) && (event.keyCode <= 90) || (event.keyCode >= 97) && (event.keyCode <= 122) || (event.keyCode >= 48) && (event.keyCode <= 57))){
        event.returnValue = false;
        return;
    }
    event.returnValue = true;
}

use this this will fix the issue使用这个这将解决问题

String patttern = r"[!-/:-@[-`{-~]";字符串模式 = r"[!-/:-@[-`{-~]";

RegExp regExp = RegExp(patttern); RegExp regExp = RegExp(patttern);

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

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