2

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+\]))
Unihedron
  • 10,902
  • 13
  • 62
  • 72

2 Answers2

2

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.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
  • 1
    I like the 2nd approach plus – Jonny 5 Sep 21 '14 at 04:26
  • Me too, the first approach incurs extra time asserting that the same group is absent multiple times, that part cannot be optimized away. On the other hand, backtracking gets the job done faster, especially if the match is far back. – Unihedron Sep 21 '14 at 04:26
  • Thanks a lot!! It works for me! ... and i'm using for a replace! – Marcel Piva Sep 21 '14 at 04:32
1

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)
hwnd
  • 69,796
  • 4
  • 95
  • 132