0
votes

In C# I'm trying to replace characters in a string. To be more precise, wherever there is a double quote which is NOT followed, nor preceded, by a comma, I'd like to replace that double quote with a single quote. So, for example:

John",123

and 123,"John

are both fine, because there is a comma either before or after the double quote, but:

John"Marks

is not fine because there is a double quote which is neither preceded not succeeded by a comma, so it should be replaced with a single quote. I.e. it should become:

John'Marks

I'm struggling to figure this one one... any ideas anyone? Thanks...

1

1 Answers

6
votes

You can use look arounds for your search regex:

(?<!,)"(?!,)

RegEx Demo

RegEx Breakup:

  • (?<!,) - Negative Lookbehind to assert previous character is not a comma
  • " - Match a double quote
  • (?!,) - Negative Lookahead to assert next character is not a comma

Replacement string would be just a single quote "'"

Code:

string repl = Regex.Replace(str, @"(?<!,)\"(?!,)", "'");