Sudhir G
Sudhir G

Reputation: 381

Regular Expression Formula Parsing in javascript

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.

Upvotes: 1

Views: 87

Answers (1)

adelriosantiago
adelriosantiago

Reputation: 8124

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 $

Upvotes: 1

Related Questions