C#ReadLine转义回车/换行? [英] C# ReadLine escapes carriage return/newline?

查看:1323
本文介绍了C#ReadLine转义回车/换行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我写了一个非常简单的C#程序的命令行,而不是依赖使用的MS Word中搜索C#正则表达式和替换。问题是,当我使用\r\\\
作为Regex.Replace的通过到Console.ReadLine()替换字符串的它与第4个字符\r\\\
取代,而不是一个真正的回车换行。不过,如果我写的字符串替换=\r\\\
它的作品如预期,即替换回车换行的字符串。一个例子输入字符串将是伍德科克,美国(后跟\r\\\
)。由于代码是它会产生Woodstock\r\\\
。这里是我的代码:

  [STAThread] 
静态无效的主要(字串[] args)
{
串初始= Clipboard.GetText();
Console.Write(查找:);
串找到=到Console.ReadLine();
Console.Write(替换);
字符串替换=到Console.ReadLine();
串最终= Regex.Replace(初始,查找,替换);
System.Threading.Thread.Sleep(3000);
Clipboard.SetText(最后一次);
}


解决方案

如果您未逸出替换(也可能是找到),它应该做你所需要的。

 字符串初始=伍德斯托克音乐节,美国+ Environment.NewLine; 
Console.Write(查找:);
串找到=到Console.ReadLine();
Console.Write(替换);
字符串替换=到Console.ReadLine();
代替= Regex.Unescape(替换);
串最终= Regex.Replace(初始,查找,替换);

Console.WriteLine(初始:{0}(开始){0} {1} {0}(END){0},Environment.NewLine,初始);
Console.WriteLine(总决赛:{0}(开始){0} {1} {0}(END){0},Environment.NewLine,最终);
到Console.ReadLine();



控制台I / O:

 
查找:伍德斯托克
替换:Woodstock\r\\\

初始:
(开始)
伍德斯托克,美国

(END)

决赛:
(开始)
伍德斯托克
,美国

(END)

MSDN Regex.Unescape


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

解决方案

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

这篇关于C#ReadLine转义回车/换行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆