Search code examples
javascriptregexstringreplace

Regex (regular expressions), replace the second occurence in javascript


This is an example of the string that's being worked with:

xxxxxx[xxxxxx][7][xxxxxx][9][xxxxxx]

I'm having a little trouble matching the second occurrence of a match, I want to return the 2nd square brackets with a number inside. I have some regex finding the first square backets with numbers in a string:

\[+[0-9]+\]

This returns [7], however I want to return [9].

I'm using Javascript's replace function, the following regex matches the second occurrence (the [9]) in regex testeing apps, however it isn't replaced correctly in the Javascript replace function:

(?:.*?(\[+[0-9]+\])){2}

My question is how do I use the above regex to replace the [9] in Javasctipt or is there another regex that matches the second occurrence of a number in square brackets.

Cheers!


Solution

  • If xxx is just any string, and not necessarily a number, then this might be what you want:

    (\[[0-9]+\]\[.*?\])\[([0-9]+)\]
    

    This looks for the second number in []. Replace it with $1[<replacement>]. Play with it on rubular.

    Your regular expression fails to work as intended because groups followed by + only end up holding the last [xxx].