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

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.


Need Your Help

Codeigniter Calling Controller with data from a form issue

php codeigniter controller

Trying to call the projects controller and the editproject function and pass an id number. Can anyone tell me why the second line doesn't work? When I echo the value in the first line, it does give...

Using a 'where' statement in Linq only when a variable has a value

c# asp.net linq

I have a linq query that is creating a list. I only want to use the second where clause if affiliationID != 0. Any tips?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.