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

How do I use RegEx to leave numbers and math operators inside of parenthesis

Using Javascript and RegEx, how I can start with something like this…

((5 dogs + 2 cats) * $3.00 per animal) + $20 flat fee

…and end up with just the math operators (allowing for both x and * for multiplication), dollar signs, decimal points, spaces and numbers…

(5 + 2) * $3.00) + $20

Ideally, there would be two levels of nesting max; but if that’s not possible, one level would also be useful.

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

>Solution :

You could use a string replace using a regular expression matching only symbols different from the allowed characters: +-*/[0-9]$() to be replaced with empty string.

Here’s a demo:

const formula = "((5 dogs + 2 cats) * $3.00 per animal) + $20 flat fee";
const result = formula.replace(/[^-+*\/()\d$]/img, "");

console.log(result);
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