Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
First, remove all non-brackets from the string (that is, find the regular expression
Recursive expressions work
\( (?: [^()] *+ | (?0) )* \)
in some languages: You can cheat in some languages (PERL):
$regex = qr/
\(
(
[^()]+
|
(??{$regex})
)*
\)
/x;
re = %r{
(?<re>
\(
(?:
(?> [^()]+ )
|
\g<re>
)*
\)
)
}x
Even if it is possible, then you should not check it with them, with the help of the stack it will all go faster, easier and more understandable.
In PHP:
$balanced = !preg_match("/[()]/", preg_replace("/\((((?>[^()]+)|(?R))*)\)/", " ", $string));
It including for lines of a look: aaa(bb)cc
But it is a perversion, it is better to do as Mithgol wrote.
It is better not to do it through regular expressions. See also Chomsky hierarchy and here .
This problem is unsolvable in regular expressions and in finite automata (equivalent means), it requires a push-down automaton, that is, a stack. Although if the maximum depth of brackets is limited, then some ugly solution can probably be invented.
Regexp is not the means by which you need to solve such a problem. They are not designed to work with nested/recursive structures.
Theoretically, of course, you can go crazy and come up with a solution. It all depends on how "smart" the algorithm should be.
The correct solution for the simple case (when nothing else is required other than bracket checking) is a simple function in your favorite language that counts brackets. For more advanced cases, a library for lexical / parsing.
Well, as an option, you can use this expression \((?=[^\(]*\)).*?\) to consistently replace all brackets with spaces (it removes the most nested bracket), and then search in the string "(" or ")", if found, means the balance of the curve.
But it's easier to balance two counters and one pass along the line :)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question