use re 'debug'; $np = qr{ \( (?: (?> [^()]+ ) # Non–parens without backtracking | (??{ $np }) # Group with matching parens )* \) }x; $funpat = qr/\w+$np/; "fun(1,(2),5)" =~ /^$funpat$/; #Matches!"