您好我写了一个非常简单的C#程序的命令行,而不是依赖使用的MS Word中搜索C#正则表达式和替换。问题是,即使正则表达式识别\r和\\\很好,当我尝试使用其中任一来替换字符串,它似乎与转义字符,而不是字符本身来取代它。
[STAThread] 静态无效的主要(字串[] args) {串初始= Clipboard.GetText (); Console.Write(查找:); 串找到=到Console.ReadLine(); Console.Write(替换); 字符串替换=到Console.ReadLine(); 串最终= Regex.Replace(初始,查找,替换); Clipboard.SetText(最后一次); }例如,从剪贴板中我输入的字符串将是伍德科克,美国 (在末尾回车换行)。这个模式将是@+ \r,它匹配的罚款,并替换字符串会@\r\\\。这产生字符串Woodcock\r\\\(这是字母R和n仅仅是明确的)。我在做什么错
编辑: Anirudh的回答解决我的问题部分,我相应更新的代码。但是,看来,当我输入\r\\\它也逃脱不知何故,而的ReadLine如果我写字符串替换=\r\\\它实际上取代了以回车换行的字符串。链接到新的问题: C#的ReadLine逃脱回车/换行符 解决方案
这是因为你使用逐字字符串即 @,这会逃脱\r\\\把它们当作文字,而不是特殊字符!
替换字符串应该是\r\\\ 不会 @\r\\\
要解决的另一个问题。
输出= Regex.Replace(输入\\r?\\\ \,\r\\\);
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 even though the Regex recognizes \r and \n fine, when I try to replace the string with either of these, it seems to replace it with the escaped character instead of the character itself.
[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); Clipboard.SetText(final); }For example, my input string from the clipboard would be "Woodcock, american" (with a carriage return-newline at the end). the pattern would be @",.+\r", which matches fine, and the replacement string would be @"\r\n". This produces the string "Woodcock\r\n" (which are the letters r and n just to be clear). What am I doing wrong?
edit: Anirudh's answer solved my problem partially and I updated the code accordingly. However, it seems that when I input "\r\n" to the ReadLine it also escapes somehow, whereas if I write string replace = "\r\n" it actually replaces the string with a carriage return-newline. Link to new question : C# ReadLine escapes carriage return/newline?
解决方案This is because you are using verbatim string i.e @"" which would escape \r\n treating them as literals and not special characters!
The replacement string should be "\r\n" NOT @"\r\n"
To solve your other problem
Output=Regex.Replace(input,"\\r?\\n","\r\n");
更多推荐
Regex.Replace rufuses与换行符替换
发布评论