使用lookahead获取javascript中模式的最后一次出现
using a lookahead to get the last occurrence of a pattern in javascript
我能够构建一个正则表达式来提取模式的一部分:
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]"]
相关文章:
- Javascript匹配以从URL中删除部分文件名-替换最后一次出现的内容
- 正在查找最后一次出现的文本
- JavaScript只有在最后一次被调用时才运行函数
- 字符串拆分并获取第一次和最后一次出现
- Regex-从第二次出现到最后一次出现
- 我如何可以忽略以前的选择,只写最后一次选择
- 异步mongodb更新循环中最后一次迭代后的重定向
- 链接超时会导致最后一次超时被拒绝
- 变量在循环的最后一次迭代中变为未定义
- 将匹配字符串中最后一次出现的点的正则表达式
- 删除/隐藏链接后最后一次出现的字符串
- 如何获取单击元素的类值,并使用此值在 jquery 中最后一次出现此类之后放置一段 html 代码
- 如何在最后一次出现某个字符后获取 url 中的参数
- 在使用 CasperJS 遍历参数化 URL 时,仅执行最后一次迭代
- 在javascript中获取除最后一次外的所有模式
- 使用lookahead获取javascript中模式的最后一次出现
- 删除javascript中最后一次出现的字符串
- Javascript Regex匹配字符串最后一次出现后的所有内容
- 使用RegEx获取最后一次出现
- Javascript 正则表达式,用于匹配从最后一次出现的模式到跨多行的不同模式