在正则表达式中添加DOT(。) [英] Adding a DOT (.) to Regular Expression

查看:87
本文介绍了在正则表达式中添加DOT(。)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下面的函数中为允许的字符添加一个():

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:


未捕获的SyntaxError:无效的正则表达式:/ [()a-zA-Z0-9
?,/ - 。] /:无序的范围字符类

Uncaught SyntaxError: Invalid regular expression: /[()a-zA-Z0-9 ?,/-.]/: Range out of order in character class

我尝试添加()&也尝试用( \。)添加它但仍然是同样的错误。

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 (.) ?

推荐答案

注意 - 应该在字符类的开头或结尾处,或者必须用反斜杠 \ 进行转义,因为它表示范围,如 az

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 a-z

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

此外,如果需要动态正则表达式,只需使用上面的正则表达式文字,如果没有,你必须删除分隔符 / / 并使用实际的正则表达式 [()a-zA-Z0-9?,/ .-] 作为字符串,可在 RegExp 构造函数。

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.

这篇关于在正则表达式中添加DOT(。)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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