我有以下两个字符串。在这两种情况下,我都试图检索“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/