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, ie 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);
}
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.