javascript - 正则表达式获取最后一个重复

标签 javascript regex

我有以下两个字符串。在这两种情况下,我都试图检索“foreclosure_defenses”。

str = "client_profile[lead_profile_attributes][foreclosure_defenses_attributes][0][own_property]"
str2 = "client_profile[foreclosure_defenses_attributes][0][own_property]"

我已经很接近了,但我无法得到一个可以与它们一起使用的正则表达式。

此正则表达式适用于 str2,但不适用于 str:

regex = /\w+(?:\[(\w+)_attributes\]+)\[\d+\]\[own_property\]/g 
regex.exec(str2)
["client_profile[foreclosure_defenses_attributes][0][own_property]", "foreclosure_defenses"]

此正则表达式适用于 str,但不适用于 str2:

regex = /\w+(?:\[(\w+)_attributes\]?)+\[\d+\]\[own_property\]/g
regex.exec(str);
["client_profile[lead_profile_attributes][foreclosure_defenses_attributes][0][own_property]", "foreclosure_defenses"]

最后一个应该适用于这两种情况,但事实并非如此。它应该寻找一个或多个 _attributes 模式并获取最后一个。 我做错了什么?

最佳答案

我想你想要

/\w+(?:\[(\w+)_attributes\])+\[\d+\]\[own_property\]/

请注意,如果您使用全局 g 标志并尝试匹配多个字符串,则需要重置正则表达式的索引。

关于javascript - 正则表达式获取最后一个重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26919093/

相关文章:

javascript - 在生产中使用 babel-node 可以吗

Javascript正则表达式正在对文字括号进行分组?

javascript - 禁用 Adob​​e Air 身份验证对话框

javascript - 使用可重用组件时 Angular 7 CSS 不工作

javascript - 如何在后台处理名为onload的javascript函数?

ruby - 交换嵌套引号的正则表达式?

javascript - JS 中的 RegEx 负前瞻

php - 正则表达式查找和替换

java - 正则表达式无法正确匹配多个单词

javascript - 从单独的 XUL 文件中引用一个 id