Match parentheses with preg_match()

10,041

Solution 1

Assuming that parentheses can't be nested, you can do this by treating digits enclosed with parentheses as if they were a single digit:

([0-9]|\([0-9]+\))*

Solution 2

Assuming you need nested parens, you can't do that with regex. What you can do, however, is to remove all non-parenthesis characters (this is trivial), so your text will look like ()()(()). From there on, you just check the resulted string. What you have to do is roughly:

for($i=0; $i<strlen($parens); $i++) {
    $paren = $parens[$i];
    if($paren == '(')
        $level ++;
    else
        $level --;
    if($level < 0) {
        // not nested correctly
        break;
    }
}
if($level != 0) // not nested correctly

Hope this helps :)

Solution 3

This is possible to solve using regular expressions. Read about recursive patterns.

Solution 4

You can use this:

^(\d|\(\d+\))+$

This assumes that nested parentheses are not allowed.

Share:
10,041
John
Author by

John

Updated on June 14, 2022

Comments

  • John
    John almost 2 years

    Possible Duplicate:
    Regex for checking if a string has mismatched parentheses?

    I'm trying to write a regex to match a string of numbers only, optionally enclosed in parentheses (regex must also check if parentheses are closed correctly, that is, if they exist in pars). So all of this should be considered valid by the regex: 1234567 123(45)6 (123)(456)

    I came up with this using conditional patterns (note that I use spaces so the x modifier is required to make it ignore spaces):

    $val = "(123)";
    $regex = "^( (\()? [0-9]+ (?(2)\)) )+$";
    $ret = preg_match("/{$regex}/x", $val, $matches);
    

    However although it matches the above "(123)" correctly, it also matches the below which it shouldnt: "(123)45)" (second number has closing parentheses only)

    Anyone can help?

    NOTE: No nested parentheses allowed

  • phant0m
    phant0m almost 13 years
    PHP manual says you can: ch.php.net/manual/en/regexp.reference.recursive.php Although I agree that regex isn't exactly pretty for this.
  • John
    John almost 13 years
    thanks! I'm pissed because I spent so much time trying to do it with conditional expressions when the solution is so short and simple.