5

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1, was about to add replace(/(.*)/,"") to previous answer but deleted it because you say same idea with a correct regex, taking into account its "greedy" nature
Cool. Thank you! I don't care about efficience, because string is short.
0

You can use indexOf() and lastIndexOf() to detect the out-most parenthesis so that you can get rid of what you want.This works with indefinite parenthesis

1 Comment

That fails on this expression: "2 (not 3) and 3 (not 4)". You would actually need a stack or something similar to keep track of the left parens seen so far, popping whenever you see a right paren.
0
(?=(\d+[\d.*]*)(?![^(]*?\)))\1

(?=( starts capturing a group using a look forward

(\d+[\d.*]*)

is the capture group for your number

(?![^(]*?\))

is a negative forward lookup that makes sure there isn't an open parenthesis after the number

)\1

look forward ends here match the found number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.