1

I'm trying to build a regex to parse excel expressions, something very simple like this:

SUM(1;2;SUM(999);SUM(3;4);SUM(9))

The regex should match all the SUM functions, so I can parse them later. So far this is what I have

(SUM\(.*?\))

But it doesnt match SUM(999), only the other SUM functions. Im fairly new to regular expressions so I dont know what I'm doing wrong. Can anybody help me?

Thanks!

https://regex101.com/r/ge6TTJ/1/

Fabio K
  • 1,297
  • 4
  • 13
  • 24
  • What should be the expected matches? Is that entire input string or part of it? – revo Jun 24 '18 at 22:24
  • I need all the matches shown in the picture, plus SUM(999). My problem is... why isnt SUM(999) being matched? – Fabio K Jun 24 '18 at 22:33
  • This might be helpful: https://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns – Mark Jun 24 '18 at 22:47

1 Answers1

0

SUM\([0-9\;]+\)? this regex would show you every SUM expression without the need of enclosing paranthesis.

Code:

let data = "SUM(1;2;SUM(999);SUM(3;4);SUM(9))";
let match = data.match(/SUM\([0-9\;]+\)?/gm)

Result:

["SUM(1;2;", "SUM(999)", "SUM(3;4)", "SUM(9)"]

If you would like to fullfill enclosing paranthesis you can do something like that:

let data = "SUM(1;2;SUM(999);SUM(3;4);SUM(9))";
let match = data.match(/SUM\([0-9\;]+\)?/gm).map(r => r.slice(-1) === ")" ? r : r.concat(")"))

Result:

["SUM(1;2;)", "SUM(999)", "SUM(3;4)", "SUM(9)"]
aprogrammer
  • 1,764
  • 1
  • 10
  • 20