1

So I have this regex: /.+\[[0-9]+\]/g
and this string hello[0][1][3]

And I am trying to split that into - hello[0], hello[0][1] and hello[0][1][3] using regex.exec(...) but I am getting hello[0][1][3] as the only match.

How can I modify the regular expression to get the desired result

Tony
  • 31
  • 5

1 Answers1

0

You could make use of a capturing group with an infinite quantifier inside a positive lookbehind. See Lookbehind in JS regular expressions for the browser support.

(?<=(\w+(?:\[\d+])+))(?=\[|$)

Explanation

  • (?<= Positive lookbehind, assert what is on the left is
    • ( Capture group 1
      • \w+(?:\[\d+])+ Match 1+ word chars, and repeat 1+ times 1+ digits between square brackets
    • ) Close group
  • ) Close lookbehind
  • (?=\[|$) Positive lookahead, assert what is directly to the right is either [ or the end of the string

Regex demo

let regex = /(?<=(\w+(?:\[\d+])+))(?=\[|$)/g;

[
  "hello",
  "hello[0]",
  "hello[0][1]",
  "hello[0][1][3]",
  "hello[0][1][3][2]"
].forEach(s => {
  while ((m = regex.exec(s)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
      regex.lastIndex++;
    }
    console.log(m[1]);
  }
  console.log("-----------------");
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70