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.
\[(\d+)\](?:(?!\[\d+\]))
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.
\[(\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)