C# ReadLine escapes carriage return/newline?

2019-07-24 16:11发布

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);
    }

1条回答
仙女界的扛把子
2楼-- · 2019-07-24 17:15

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)

MSDN Regex.Unescape

查看更多
登录 后发表回答