Reputation: 3
I have these variables below :
let x = '5(2+1(3(4-1))';
let y = [];
I need to extract any string between ()
and push to array
to be output like:
console.log(y); // Array should be y[4-1,3,2+1,5]
How I can solve this?
Upvotes: 0
Views: 125
Reputation: 6524
try with this regex
let x = '5(2+1(3(4-1))';
let y = [];
let regex = /\(?(\d+([+-]\d+)?)/gm;
let m
while ((m = regex.exec(x)) !== null) {
y.push(m[1])
}
y = y.reverse()
console.log(y)
Upvotes: 1
Reputation: 7600
This can be accomplished by recursivly applying a regex getting and replacing the inner most () pair until only the last 5 is left, or by building a real parser.
Depending on how the input can look regex might not work.
But there exist no simple solution and it will depend on exactly what format you might get.
Upvotes: 0