While working on some regex, I encountered a bug:
The scenario is as follows: I have this string - for example
"+1/(1/10)+(1/30)+1/50"
and I applied the regex /\+.[^\+]*/g
to it,
which worked perfectly giving me
['+1/(1/10)', '+(1/30)', '+1/50']
https://i.sstatic.net/tggcj.png
However, the real issue arises when the +
is within the parentheses ()
For example:
"+1/(1+10)+(1/30)+1/50"
https://i.sstatic.net/1BRkS.png
This results in
['+1/(1', '+10)', '+(1/30)', '+1/50']
, which is not the desired output... What I want is ['+1/(1+10)', '+(1/30)', '+1/50']
So, the question is how can I ignore the parentheses in regex?
Any suggestions on how to accomplish this in regex?
Here is my Javascript code:
const tests = {
correct: "1/(1/10)+(1/30)+1/50",
wrong : "1/(1+10)+(1/30)+1/50"
}
function getAdditionArray(string) {
const REGEX = /\+.[^\+]*/g; // need to modify this regex to ignore the () even if they contain the + sign
const firstChar = string[0];
if (firstChar !== "-") string = "+" + string;
return string.match(REGEX);
}
console.log(
getAdditionArray(test.correct),
getAdditionArray(test.wrong),
)