(?: (?{ local $d=0 }) # set depth to 0 ( # start capture (?: \( # opening paren (?{$d++}) # increment the depth | \) # or closing paren (?{$d--}) # decrement the depth (?(?{$d==0}) # if we're back to the start (*ACCEPT) # we're done ) | (?>[^()]*) # or there's just some normal text )* (?(?{$d!=0}) # done. did we reach a matching closing paren (?!) # nope, failed ) ) # end capture )