0

I need to parse this java script formula

Original Formula:

sum((a+b)*c)+count((a*c)+b)+avg((a-c)/b)+sum((a-c+d)/b)

expected result:

a = (a+b)*c
b = (a*c)+b
c = (a-c)/b
d = (a-c+d)/b 

What ever we tried is in the link below, please check the link.

https://regex101.com/r/upnlkA/2/

Any Help will be Appreciated, Thanks in Advance.

Sudhir G
  • 53
  • 1
  • 4
  • Can the parentheses be nested only one level deep like in the example, or arbitrarily deep? – CertainPerformance Apr 13 '20 at 06:09
  • Regex is generally not suitable for parsing a nested arithmetic formula. On top of this, I don't understand whence the LHS in your expected output are coming. – Tim Biegeleisen Apr 13 '20 at 06:09
  • Please check out this related question matching balanced parentheses. It seems to work for what you need: https://stackoverflow.com/questions/546433/regular-expression-to-match-balanced-parentheses#answer-19863847 – Eduardo Lelis Apr 13 '20 at 06:16
  • The LHS Doest matter for the purpose of understanding i just added that the result i expect is the same "(a+b)*c" please ignore the LHS part and Thanks for your response @TimBiegeleisen – Sudhir G Jun 04 '20 at 06:15

1 Answers1

0

First off, if the structure of the formula is expected to change then you should not use a regex. If this is the case you should use a package like extract-brackets.

If the formula is not going to change its structure considerably then you can use this regex:

/\w{2,}\((.+?)\)(?=(\+\w{2,}|$))/gm

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

It will give you the following groups:

  • (a+b)*c
  • (a*c)+b
  • (a-c)/b
  • (a-c+d)/b

You can find the detailed explanation in the link. The human-readable explanation is that it looks for words with 2 or more characters \w{2,}, begins extracting and stops until it finds another word with 2 or more characters or the end of the string $

adelriosantiago
  • 6,469
  • 6
  • 30
  • 62