Using Regex Replace when looking for un-escaped characters

Posted by Daniel Hollinrake on Stack Overflow See other posts from Stack Overflow or by Daniel Hollinrake
Published on 2012-11-16T16:46:40Z Indexed on 2012/11/16 16:59 UTC
Read the original article Hit count: 393

Filed under:
|
|

I've got a requirement that is basically this. If I have a string of text such as

"There once was an 'ugly' duckling but it could 
never have been \'Scarlett\' Johansen"

then I'd like to match the quotes that haven't already been escaped. These would be the ones around 'ugly' not the ones around 'Scarlett'.

I've spent quite a while on this using a little C# console app to test things and have come up with the following solution.

private static void RegexFunAndGames() {

  string result;
  string sampleText = @"Mr. Grant and Ms. Kelly  starred in the film \'To Catch A Thief' but not in 'Stardust' because they'd stopped acting by then";
  string rePattern = @"\\'";
  string replaceWith = "'";

  Console.WriteLine(sampleText);

  Regex regEx = new Regex(rePattern);
  result = regEx.Replace(sampleText, replaceWith);

  result = result.Replace("'", @"\'");

  Console.WriteLine(result);
}

Basically what I've done is a two step process find those characters that have already been escaped, undo that then do everything again. It sounds a bit clumsy and I feel that there could be a better way.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET