Sergey
Sergey

Reputation: 49758

Regular expression that matches any string parenthesized n times

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

Answers (2)

Brigand
Brigand

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!");
}

demo

Upvotes: 1

amit
amit

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

Related Questions