I have a regex expression: /diff\\left\((...*?\\right\){0,1})\\right\)/gm and the string I want to match is diff\left(5x^2\right) + diff\left(5x^2+\tan\left(x\right)\right).
I want to match in such a way that there are two matches diff\left(5x^2+\right) and diff\left(5x^2+\tan\left(x\right)\right) each having captured groups 5x^2 and 5x^2+\tan\left(x\right). I want to add \right) inside a captured group once only if it occurs twice. However, I'm only getting a single match with the entire 5x^2\right)+diff\left(5x^2+\tan\left(x\right) inside a captured group. Here are two images to better understanding. Blue parts represent matches and green parts represent captured groups
Here is the output I'm getting
The first image is a screenshot from regex101 and the second one is an edited image
Please help me with this I'm trying to build a symbolic calculator app. Thanks
If those two parts are to always be bound by space characters, you could try something like the below:
https://regex101.com/r/Lcsxxv/1
const regex = /diff\\left\(([^ ]*)\\right\)/gm;
const str = `diff\\left(5x^2\\right) + diff\\left(5x^2+\\tan\\left(x\\right)\\right)`;
const matches = [];
const groups = [];
let r;
while ((r = regex.exec(str)) !== null) {
matches.push(r[0]);
groups.push(r[1]);
}
console.log(`matches:\n\t${matches.join('\n\t')}
groups:\n\t${groups.join('\n\t')}`)
The way it works is that it's going to look for the last instance of \right) until either the end of the string or a space character, whichever comes first.
I hope this answers your question.