Matching for {[^}]+}
Matching simple code in the exception handler, provided there are no nested curly braces:
catch *\((\w+)\) *{[^}]+(\1)(\.stack)[^}]+}
The above regular expression matches these examples
(capturing groups for my sake, remove them if not needed):
try {
print(new Function (astatement)())
} catch (e) { print(e.stack) }
try {
print(new Function (bstatement)())
} catch (exception) { print(exception.stack) }
You can try it out here:
https://regex101.com/r/PuytDJ/2
Some techniques used here
\w+
Instead of just .
I assume you can give the exception instance any name, so maybe more safe to use \w+
here.
{[^}]+
This looks for an opening curly brace and catches every non-closing curly brace until the next expression. It works only if you do not have nested curly braces in your exception handler.
(\1)
Here I reference the exception's variable name found in capturing group 1.
(\.stack)
Here is finding .stack
literally
[^}]+}
I continue to parse for all non-curly braces characters and finally the closing curly bracket.
Disclaimer
⚠ This being said, regular expressions cannot parse nested elements very well, or only to a certain degree with increasingly more complex expressions.
So code blocks, HTML/XML Tags, JSON objects etc. are better parsed, not text-searched in.