javascript中字符类出现乱序 [英] Range out of order in character class in javascript

查看:55
本文介绍了javascript中字符类出现乱序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么我的正则表达式不正确:

I don't know why my regex is incorrect:

var domain = "google\.com\.br";
var reEmail = new RegExp("^([A-Za-z0-9_\-\.])+\@" + domain + "$");

我需要这个来验证电子邮件.下面的示例:reEmail.test("contact@google.com.br");

I need this to validate an email. Example below: reEmail.test("contact@google.com.br");

我收到此错误:

角色类出现乱序

推荐答案

由于使用字符串创建RegExp,因此_\-\.变为_-.,这是无效范围. (这是从_.的范围,这是不正确的)

Because you create the RegExp using a String the _\-\. becomes _-. and that is the invalid range. (It is a range from _ to . and that is not correct)

您需要两次逃脱:

new RegExp("^([A-Za-z0-9_\\-\\.])+@" + domain + "$");

这样,\\在字符串中成为\,然后用于在RegExp中转义-.

That way the \\ becomes a \ in the String and then is used to escape the -in the RegExp.

如果您通过String创建RegExp,则记录结果总是有帮助的,这样可以查看您是否做对了所有事情:

If you create RegExp by String it is always helpful to log the result so that you see if you did everything right:

例如您的RegExp一部分

e.g. your part of the RegExp

console.log("^([A-Za-z0-9_\-\.])+\@");

导致:

^([A-Za-z0-9_-.])+@

这篇关于javascript中字符类出现乱序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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