Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

evaluate `resin(x)` function in string with regular expression

I am trying to evaluate a function in a string like this resin(8)

so if i have this text 3*(resin(4)-sin(12))

I need to evaluate resin(1) so it will replace that while occurrence with the result which should look like 392.9

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am using this

result = result.replace(/(?<={resin\()(.*?)(?=\)})/, x => parseInt(392.9 * x))

but i need it to replace the resin( part and the ) closing parentheses.

is there any regexp magic I can use?

>Solution :

Are you sure you need a positive lookbehind and a positive lookahead?

In my opinion, when using a regex replacer, as you did, the grouping is more than enough to accomplish the task:

result = result.replace(/resin\((\d+\.?\d*)\)/g, (_, x) => parseInt(392.9 * parseFloat(x)))

Edit:
I just read in your question that you need resin(1) to be replaced with 392.9, but in your snippet you used parseInt and I kept it in my example. Just drop the parseInt in case you don’t need the result to be an integer

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading