JavaScript 正则表达式异常(无效组)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4200157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:21:17  来源:igfitidea点击:

JavaScript regular expression exception (Invalid group)

javascriptregex

提问by Maksim Vi.

I have the following regular expression:

我有以下正则表达式:

/(?<={index:)\d+(?=})/g

I am trying to find index integer in strings like this one:

我试图在这样的字符串中找到索引整数:

some text{index:1}{id:2}{value:3}

That expression works fine with php, but it doesn't work in javascript, I get the following error:

该表达式适用于 php,但不适用于 javascript,我收到以下错误:

Uncaught SyntaxError: Invalid regular expression: /(?<={index:)\d+(?=})/: Invalid group

Uncaught SyntaxError: Invalid regular expression: /(?<={index:)\d+(?=})/: Invalid group

What do I need to fix?

我需要修复什么?

Thanks.

谢谢。

采纳答案by Phrogz

var str = "some text{index:1}{id:2}{value:3}";
var index = str.match(/{index:(\d+)}/);
index = index && index[1]*1;

回答by mike

(?<= )is a positive lookbehind. JavaScript's flavor of RegEx does not support lookbehinds (but it does support lookaheads).

(?<= )是积极的回顾。JavaScript 的 RegEx 风格不支持lookbehinds(但它支持lookaheads)。

回答by cdhowie

JavaScript does not support look-behind assertions. Use this pattern instead:

JavaScript 不支持后视断言。请改用此模式:

/{index:(\d+)}/g

Then extract the value captured in the group.

然后提取在组中捕获的值。