if (/^(.*?)(?:_([^_]*))?\.pdf$/) { # do something with $1 and $2 }