Reputation: 852
Hi I wrote a very simple C# program to use the C# Regex from command line instead of relying on the MS Word search and replace. The problem is that when I use "\r\n" as a replacement string in Regex.Replace through Console.ReadLine() it replaces with the th 4 characters "\r\n" instead of a real carriage return-newline. However, if I write string replace= "\r\n"
it works as intended, i.e. replaces the string with a carriage return-newline. An Example input string would be "Woodcock, american" (followed by \r\n). As the code is it produces "Woodstock\r\n". Here is my code:
[STAThread]
static void Main(string[] args)
{
string initial = Clipboard.GetText();
Console.Write("Find: ");
string find = Console.ReadLine();
Console.Write("Replace: ");
string replace = Console.ReadLine();
string final = Regex.Replace(initial, find, replace);
System.Threading.Thread.Sleep(3000);
Clipboard.SetText(final);
}
Upvotes: 2
Views: 3057
Reputation: 50235
If you unescape replace
(and possibly find
), it should do what you need.
string initial = "Woodstock, American" + Environment.NewLine;
Console.Write("Find: ");
string find = Console.ReadLine();
Console.Write("Replace: ");
string replace = Console.ReadLine();
replace = Regex.Unescape(replace);
string final = Regex.Replace(initial, find, replace);
Console.WriteLine("initial:{0}(BEGIN){0}{1}{0}(END){0}", Environment.NewLine, initial);
Console.WriteLine("final:{0}(BEGIN){0}{1}{0}(END){0}", Environment.NewLine, final);
Console.ReadLine();
Console I/O:
Find: Woodstock Replace: Woodstock\r\n initial: (BEGIN) Woodstock, American (END) final: (BEGIN) Woodstock , American (END)
Upvotes: 1