[英]How could I get the last occurrence of [0] using regular expression?
I'm trying to get the last occurrence of a situation. 我正在尝试获取情况的最后一次出现。
obj.foo[0].bar[0].name
I try this code but just got the first [0]
and if I put $
at end just doesn't work. 我尝试了这段代码,但是只得到了第一个
[0]
,如果我将$
放在最后,则无法正常工作。
\[(\d+)\](?:(?!\[\d+\]))
You have to assert that another same group cannot be somewhere after the match, not just immediately after. 您必须断言另一个同一个组不能在比赛后的某个地方 ,而不仅仅是在比赛之后的某个地方 。 See this modification:
请参阅此修改:
\[(\d+)\](?!.*?\[\d+\])
^^^
Or you can switch to a backtracking approach: 或者,您可以切换到回溯方法:
.*\[(\d+)\]
Here is a regex demo for the first regex, and here is one for the other. 这里是一个正则表达式演示了第一个正则表达式,而这里是一个为其他。
Depending if you want the brackets included, you could use the following: 根据是否要包含方括号,可以使用以下内容:
var r = s.match(/\[\d+\]/g)[1]
If you do not want the delimiters you can slice them from the group index. 如果您不希望使用分隔符,则可以从组索引中分割它们。
var r = s.match(/\[\d+\]/g)[1].slice(1,-1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.