I have this task: sum all numbers in string and perform multiplication
input: "3 chairs, 2 tables, 2*3 forks" result: 11
I already have regular expression to do this:
eval(str.match(/(\d[\d\.\*]*)/g).join(' + '))
But I want to add option to ignore numbers inside brackets "()"
input: "2 chairs, 3 tables (1 broke)" result: 5
How to do it?
Regular expressions were always pain for me :(
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the exec() and test() methods of RegExp , and with the match() , matchAll() , replace() , replaceAll() , search() , and split() methods of String .
In JavaScript, regular expressions are often used with the two string methods: search() and replace() . The search() method uses an expression to search for a match, and returns the position of the match. The replace() method returns a modified string where the pattern is replaced.
One simple way is to do a first pass and remove all parenthesized expressions.
str = str.replace(/\([^\)]*\)/g, "");
// now run your original algorithm to sum/multiply...
// ...
This is not super efficient but it does the job.
I should note that this does not handle nested parentheses, but it doesn't seem like that is required here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With