My question is somewhat similar to this question. However, my question is different because of the following:
- The question was not asked in a specific flavor.
- It doesn't contain any of the regex pattern in JavaScript flavor, except one which only validates two level of nesting.
- It only contain some algorithms, which I don't need because I'm trying to learn Regex.
I'm trying to learn Regex by validating an expression as "Balanced Parenthesis".
Balanced Parenthesis is an expression in which every
(
is closed with a corresponding)
For example, the below expressions are valid:
(1+2)*(2+5)
(1+2(3+4)-6)/(2+4)
((()))
But, (3+4()
is invalid.
For sake of simplicity, assume the terms inside the parenthesis to be digits and operators.
I'm using JavaScript regex. So, I tried the below regex. However, it doesn't worked out.
^(\((?:[^()]|\1*)\)[^()]*)+$
But, when I tried the below PCRE
regex, it worked out nicely.
^(\((?:[^()]|(?1))*\)[^()]*)+$
The only syntactical difference in both the regex was how the first capturing group was re-used: \1
in JS and (?1)
in PCRE. I know that \1
isn't a kind of subroutine
, so are there any alternatives present in JavaScript, except repeating the whole pattern again?
I know a way using variables
inside RegExp
constructor. But, my regex is nested and so that one is ruled out.