javascript中字符类中的范围乱序 [英] Range out of order in character class in javascript

查看:11
本文介绍了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");

我收到此错误:

字符类中的范围乱序

推荐答案

因为您使用 String 创建 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 + "$");

这样 \ 就变成 String 中的 ,然后用于转义 RegExp 中的 -.

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

如果您通过字符串创建 RegExp,记录结果总是有帮助的,这样您就可以查看是否做对了:

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

例如你的正则表达式部分

e.g. your part of the RegExp

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

结果:

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

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

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