在javascript中使用时正则表达式无效组错误 [英] Regex invalid group error while using in javascript

查看:196
本文介绍了在javascript中使用时正则表达式无效组错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下正则表达式检查多种类型的电子邮件地址输入

I have the following regex that checks for multiple types of email address inputs

[\W"]*(?<name>.*?)[\"]*?\s*[<(]?(?<email>\S+@[^\s>)]+)[>)]?

我把它关了我如何正则表达名称和电子邮件3 ruby中的主要电子邮件客户端?

我面临的问题是,在javascript中使用此问题时,我收到错误Uncaught SyntaxError:无效的正则表达式: / [\W ] *(? <名称> *。?)[\ ] * \s * [≤(]( <电子邮件> 中? \S + @ [^ \s>)] +)[>)]?/ :无效群组

The problem i am facing is that while using this in javascript i get an error "Uncaught SyntaxError: Invalid regular expression: /[\W"]*(?"<name>".*?)[\"]*?\s*[<(]?(?"<email>"\S+@[^\s>)]+)[>)]?/: Invalid group "

我花了一个整天试图解决这个问题,我发现问题与 lookbehind 有关javascript不支持

I spent an entire day trying to fix this and i found out that the problem has something to do with lookbehind That javascript doesn't support

我是在正则表达式表达非常糟糕,需要一些建议。有人可以指出我正确的方向。

I'm very bad at regex expressions and need some advice. Can someone please point me in the right direction.

PS:我正在尝试将此功能与jquery validate插件集成

PS: I am trying to make this function to integrate it with jquery validate plugin

Jquery验证

推荐答案

浏览器中的JavaScript通常不支持命名捕获。

JavaScript in browsers generally do not support named capture.

命名捕获位是这些(?< name> 。*?)(?< email> \S + @ [^ \s>)] +)

你可以用编号的捕获组替换命名捕获,改变这个:

You can replace named capture with numbered capture groups, changing this:

[\W"]*(?<name>.*?)[\"]*?\s*[<(]?(?<email>\S+@[^\s>)]+)[>)]?

到此:

[\W"]*(.*?)[\"]*?\s*[<(]?(\S+@[^\s>)]+)[>)]?

所以在JavaScript中看起来像这样:

So in JavaScript it would look like this:

match = subject.match(/[\W"]*(.*?)[\"]*?\s*[<(]?(\S+@[^\s>)]+)[>)]?/i);
if (match != null) {
    // matched text: match[0]
    // match start: match.index
    // capturing group 1 (name): match[1]
    // capturing group 2 (email): match[2]
} else {
    // Match attempt failed
}

请记住,捕获组只有在捕获到的东西时才会被添加。

Remember that capture groups might only be added if they capture something.

这篇关于在javascript中使用时正则表达式无效组错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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