How do I match a pattern with optional surrounding quotes?

Viewed 12163

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?

5 Answers

This is quite simple as well: (".+"|.+). Make sure the first match is with quotes and the second without.

Generally @Daniel Vandersluis response would work. However, some compilers do not recognize the optional group (") if it is empty, therefore they do not detect the back reference \1.

In order to avoid this problem a more robust solution would be:

/^("|)(pattern)\1$/

Then the compiler will always detect the first group. This expression can also be modified if there is some prefix in the expression and you want to capture it first:

/^(key)=("|)(value)\2$/
Related