How do I match a pattern with optional surrounding quotes?
How would one write a regex that matches a pattern that can contain quotes, but if it does, must have matching quotes at the beginning and end? "?(pattern)"? Will not work because it will allow patterns that begin with a quote but don't end with one. "(pattern)"|(pattern) Will work, but is repetitive. Is there a better way to do that without repeating the pattern? You can get a solution without repeating by making use of backreferences and conditionals : /^(")?(pattern)(?(1)\1|)$/ Matches: pattern "pattern" Doesn't match: "pattern pattern" This pattern is somewhat complex, however. It first