简体   繁体   English

将DOT(。)添加到正则表达式

[英]Adding a DOT (.) to Regular Expression

I'm looking to add a ( . ) to the allowed characters in my function below: 我想在下面的函数中将( . )添加到允许的字符中:

$(id).bind('keypress', function(event) {
    var regex = new RegExp("[()a-zA-Z0-9 ?,/-]");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (!regex.test(key)) {
        event.preventDefault();
        return false;
    }
});

However, every time I add it it comes up with the error: 但是,每次添加时都会出现错误:

Uncaught SyntaxError: Invalid regular expression: /[()a-zA-Z0-9 ?,/-.]/: Range out of order in character class 未捕获的SyntaxError:正则表达式无效:/ [()a-zA-Z0-9?,/-。] /:字符类中的范围乱序

I've tried adding just ( . ) & also tried adding it with ( \\. ) but still the same error. 我试过仅添加( . ),也尝试将其与( \\. )添加在一起,但仍然存在相同的错误。

Please can you assist to where I need to add this ( . ) ? 请您协助我在哪里添加此( . )?

Note that - should either be at the beginning or at the end of character class or has to be escaped by a backslash \\ , since it indicates range as in az 注意-应该在字符类的开始或结尾处,或者必须用反斜杠\\进行转义,因为它表示范围,az

/[()a-zA-Z0-9 ?,/.-]/

Also, if dynamic regex is required, just use the regex literal as in above, if not you'd have to remove the delimiters / / and use the actual regex [()a-zA-Z0-9 ?,/.-] as a String which can be used in RegExp constructor. 另外,如果需要动态正则表达式,则只需使用上面的正则表达式文字,否则就不必删除定界符/ /并使用实际的正则表达式[()a-zA-Z0-9 ?,/.-]作为可在RegExp构造函数中使用的String

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

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