1

I want to replace double quotes with single quotes if they aren't surrounded by single qoutes using PCRE. Some examples, the meaning is input => output

"foo" => 'foo'
'foo' => 'foo'
abc "foo" => abc 'foo'
foo "bar", "baz" => foo 'bar', 'baz'
abc 'foo "bar" baz' => abc 'foo "bar" baz'

I tried ^([^'"]*)"([^'"]*)" with the modifiers m multi-line and 'g global`. This works as far as there isn't more than one "xyz" block per line (fails in line 4).

EDIT: I forgot to mention that my current substitution is $1'$2'

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Andy
  • 7,931
  • 4
  • 25
  • 45

1 Answers1

3

The solution below will only work in case input strings have no escape sequences:

/'[^']*'(*SKIP)(*F)|"/

See the regex demo

  • '[^']*' - match a single quote, 0+ chars other than a single quote and a single quote again
  • (*SKIP)(*F) - PCRE verb sequence discarding the match and proceeding from the current index (you can read more on that at How do (*SKIP) or (*F) work on regex? SO post)
  • | - or...
  • " - a double quote.

In case there are escape sequences, you need to write a parser.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563