Reputation: 49758
For example, it should match (aaa)
, ((aaa))
, (((aaa)))
, but not ((aaa)
or (aaa))
.
Is it even possible?
P.S. If it matters, I need this regular expression for JavaScript.
Upvotes: 1
Views: 352
Reputation: 86240
If you're willing to do a little more than regex (and I mean just a little), you can use this function.
check_parens('(((aaa)))');
check_parens('((aaa)))');
check_parens('aaa');
function check_parens(hay) {
var re = /(\(+)(?:[^)]+)(\)+)/g;
var matches = re.exec(hay);
if (matches === null || matches[1].length !== matches[2].length)
alert("Too bad...");
else
alert("We're good!");
}
Upvotes: 1
Reputation: 178451
The language you are describing is context free and not a regular language, thus there is no such regular expression. One can easily show a homomorphism to L={a^n * b^n}
for this language, and L
is a well known irregular language.
It might be possible with some regex expansions, but not in standard regular expression, which originally standed for regular languages.
Upvotes: 1