Mono’s Regex.Replace

I happen to run into a difference in implementation between the Mono project’s implementation of .Net and Microsoft’s. It seems that escaped strings are handled differently in Regex.Replace when the escaped string is the replacement string. What does this mean? The following code …


string replaced = Regex.Replace( "I like the backslash", "backslash", @"\\" );
Console.WriteLine(replaced);

will output “I like the \” under Mono and “I like the \\” under MS .Net. This has been reported here, but the response was that Microsoft’s implementation is “buggy and doesn’t honour escape sequences in the replacement patterns, even though the SDK claims otherwise.”

I am only using Mono on Linux, so for now I will create a little hack that will check if my OS is Linux (Unix) or not and fix the string if it is.


string replaceWith = @"\\";
if( Environment.OSVersion.Platform == PlatformID.Unix )
{
replaceWith = Regex.Escape(replaceWith);
}
string replaced = Regex.Replace( "I like the backslash", "backslash", replaceWith);
Console.WriteLine(replaced);

Comments are closed.