使用lookahead获取javascript中模式的最后一次出现

using a lookahead to get the last occurrence of a pattern in javascript

本文关键字:最后一次 模式 lookahead 获取 javascript 使用      更新时间:2023-09-26

我能够构建一个正则表达式来提取模式的一部分:

var regex = /'w+'[('w+)_attributes']'['d+']'[own_property']/g;
var match = regex.exec( "client_profile[foreclosure_defenses_attributes][0][own_property]"  );
match[1] // "foreclosure_defenses"

然而,我也有一种情况,会有这样的重复模式:

"客户端_文件[lead_profile_attributes][止赎_防御_属性][0][自身_财产]"

在这种情况下,我想忽略[lead_file_attributes],只提取最后一次出现的部分,就像我在第一个例子中所做的那样。换句话说,在这种情况下,我仍然希望匹配"止赎_防御"。

由于所有的模式都会像[(''w+)_attributes]一样,我试着做了一个前瞻,但它不起作用:

var regex = /'w+'[('w+)_attributes'](?!'[('w+)_attributes'])'['d+']'[own_property']/g;
var match = regex.exec("client_profile[lead_profile_attributes][foreclosure_defenses_attributes][0][own_property]");
match // null

match返回null,这意味着我的regex没有按预期工作。我添加了以下内容:

'[('w+)_attributes'](?!'[('w+)_attributes'])

因为我只想匹配以下模式的最后一次出现:

[lead_profile_attributes][foreclosure_defenses_attributes]

我只想抢止赎_辩护,而不是线索_文件。

我可能做错了什么?

我想我让它在没有积极展望的情况下工作:

regex = /('[('w+)_attributes'])+/
/('[('w+)_attributes'])+/
match = regex.exec(str);
["[a_attributes][b_attributes][c_attributes]", "[c_attributes]", "c"]

我也能够通过非捕获组来实现它。铬控制台输出:

var regex = /(?:'w+('['w+']'['d+'])+)('['w+'])/;
undefined
regex
/(?:'w+('['w+']'['d+'])+)('['w+'])/
str = "profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]";
"profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]"
match = regex.exec(str);
["profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]", "[properties_attributes][0]", "[other_stuff]"]