Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex regular expression in JavaScript

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 :(

like image 823
Ildar Avatar asked Nov 30 '11 04:11

Ildar


People also ask

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What are regular expressions in JavaScript?

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 .

Does JavaScript have regular expression?

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.


1 Answers

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.

like image 84
bobbymcr Avatar answered Sep 30 '22 10:09

bobbymcr