\$ # Our '$' prefix (?: # Optionally *don't* find the opening paren. | (\() # Optionally find the opening paren ) (\w+) # The middle part is captured in $2 (?(1)\)) # Require a closing paren only if $1 matched.