I need to capture two matches between an equal sign: (test1)=(test2) such that match1 = test1 and match2 = test2. So far I have been able to use ([\s\S)(]*?)/gmi which mostly works UNLESS there is an additional close paren on either side of the equal sign, ie: (test1)=(te)st2).
What regex could I create that would allow me to successfully wind up with two matches given the below:
"(test1)=(tes=)t2)".match( /\([\s\S\)\(]*?\)/gmi ) === ["test1", "tes=)t2"]
CodePudding user response:
For the examples in the question and if supported using lookarounds, you can assert that the closing parenthesis can not contain =
or )
to the right.
Note that you can omit the /m
flag as there are no anchors in the pattern, and you can also omit the /i
flag as the pattern does not specifically matches upper or lowercase characters.
let regex = /(?<=\().*?(?=\)(?![^\s=)]))/g;
let str = "(test1)=(tes=)t2)";
console.log(str.match(regex));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Or using a capture group without a lookbehind assertion:
let regex = /\((.*?)\)(?![^\s=])/g;
let str = "(test1)=(tes=)t2)";
const result = Array.from(str.matchAll(regex), m => m[1]);
console.log(JSON.stringify(result) === JSON.stringify(["test1", "tes=)t2"]));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>