Is it possible to reuse a matching RegExp
sub-pattern for a variety of opening and closing conditions of the containing pattern?
I have a complex/long RegExp
sub-pattern for a certain expression X, which I expect to reside within any of the open-close statements, defined as: ${...}
, $(...)
, $[...]
, $/.../
, etc., which in combination makes the whole pattern (mixing open-close conditions is not accepted, or it would have been trivial).
What I want is to avoid repeating the same long X sub-pattern for each of the open-close conditions (using |
) when defining the whole pattern, as it becomes too long and unreadable, even though it is mostly just repeated X sub-pattern.
My question - is this achievable within the RegExp
syntax? And if yes, then how?
Environments: Node 0.12 for ES5 and IO.js 2.0 for ES6.
P.S. Strictly speaking, we are talking RegExp
optimization here, for better code readability, and, possibly, performance.
You can use an extremely hacky way of matching specific opening and closing braces when used together:
\$(?:(\[)|(\()|({)|(\/)).*?(?:(?=\2)(?=\3)(?=\4)\]|(?=\1)(?=\3)(?=\4)\)|(?=\1)(?=\2)(?=\4)}|(?=\1)(?=\2)(?=\3)\/)
^^^ Inner Match Here
It basically looks for all groups except one specific one to be empty and happens to only work in JavaScript regex. The .*?
section pointed out in the above code just needs to be replaced with the regex to be matched inside of the braces to match an arbitrary pattern.
Demo: https://regex101.com/r/aX7rH1/1
// Matches
${...}
$(...)
$[...]
$/.../
// Does Not Match
${...)
${...]
${.../
$(...}
$(...]
$(.../
$[...}
$[...)
$[.../
$/...}
$/...)
$/...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With