Home > Software engineering >  Regex match paramaters in array of arrays
Regex match paramaters in array of arrays

Time:01-03

Specifically I need it to do a find & replace in VSCode search.

What I have tried: buildFromArray\(\[(\s*(\[.*\]),?\s*)*

I can't seem to get the correct regex though. I have also tried using buildFromArray as a lookbehind in the regex like this: (?<=buildFromArray\(\[\s*)(?:(\[.*\]),?\n\s*)*

This works in regexr.com but vscode gives me this error:

lookbehind assertion is not fixed length

I need to match these tests:

buildFromArray([
      [1, 2, -1, -2],
      [3, 4, true, "test"],
      [2, 45, -3, -4],
])
buildFromArray([['test']], {useArrayArithmetic: true})

And produce the capture groups for the parameters like so:

[1, 2, -1, -2]

[3, 4, true, "test"]

[2, 45, -3, -4]

And:

['test']

CodePudding user response:

I'm surprised to see the VSCode is so primitive regarding Regex (I thought it used .Net Regex, but apparently not - .Net could capture repeating groups and supports look behind with var length).

So I think your best option is to repeat the pattern (and make the second and third groups optional, like this:

buildFromArray\(\[\s*(\[[^\]] \])(?:,\s*(\[[^\]] \]))?(?:,\s*(\[[^\]] \]))?

As you can see, (?:,\s*(\[[^\]] \]))? is simply repeated. It creates three groups. However, in your second test, group1 and group2 will be empty.

  • Related