regex for strings optionally surrounded with quotes

Viewed 126

I'm trying to build a regex that matches strings which are either surrounded with quotes or have no quotes at either side. Moreover, a string the regex has to match may have quotes in the middle. Here's a result of my efforts at the moment:

^("?+)(.*[^"])(\1)$

It works well with strings having quotes both at start and end, having no quotes at any side or having quotes at start only:

$ echo '"blah "blah" blah"' | perl -ne 'if(/^("?+)(.*[^"])(\1)$/){print "$1\n$2\n$3"}'
"
blah "blah" blah
"
$ echo 'blah "blah" blah' | perl -ne 'if(/^("?+)(.*[^"])(\1)$/){print "$1\n$2\n$3"}'

blah "blah" blah

$ echo '"blah "blah" blah' | perl -ne 'if(/^("?+)(.*[^"])(\1)$/){print "$1\n$2\n$3"}'

But it matches strings having quotes only at end:

$ echo 'blah "blah" blah"' | perl -ne 'if(/^("?+)(.*[^"])(\1)$/){print "$1\n$2\n$3"}'

blah "blah" blah"

Any ideas what's the problem with the regex and how to fix it?

1 Answers
Related