繁体   English   中英

用C#中的regex替换“new line”char

[英]Replace a “new line” char with regex in C#

我想在包含序列“字母或数字”,“新行”,“字母或数字”的文本文件中找到每个字符串,然后用“空格”替换“新行”。

这是我到目前为止所尝试的:

private void button3_Click(object sender, EventArgs e)
{
     string pathFOSE = @"D:\Public\temp\FOSEtest.txt";     
     string output = Regex.Replace(pathFOSE, @"(?<=\w)\n(?=\w)", " ");                      

     string pathNewFOSE = @"D:\Public\temp\NewFOSE.txt";
     if (!System.IO.File.Exists(pathNewFOSE))
     {
          // Create a file to write to. 
          using (System.IO.StreamWriter sw = System.IO.File.CreateText(pathNewFOSE))
          {                
          }
     File.AppendAllText(pathNewFOSE, output);
     }
}

但我的所有程序都是创建一个新的文本文件,只包含这行"D:\\Public\\temp\\FOSEtest.txt"

知道发生了什么事吗? 也就是\\n寻找在在Windows7一个文本文件中的新行的正确方法是什么? 谢谢

编辑 :我做了Avinash建议的更改,并补充说我正在使用Windows 7。

编辑2 :我想我需要理解为什么在路径字符串上发生Replace而不是在尝试建议之前导致的文件。

最终编辑 :感谢stribizhev一切正常,我只是复制粘贴他的答案。 感谢大家的回应!

你需要使用积极的lookbehind。

Regex.Replace(pathFOSE, @"(?<=\w)\n(?=\w)", " "); 
                            ^

(?=\\w)称为正向前瞻,它断言匹配必须后跟一个单词字符。

要么

Regex.Replace(pathFOSE, @"(?<=\w)[\r\n]+(?=\w)", " "); 

在Windows中,换行符通常看起来像\\r\\n (插入符号返回+换行符)。 因此,您可以匹配前面和后面跟有字母数字的换行符

string output = Regex.Replace(pathFOSE, @"(?<=\w)\r\n(?=\w)", " ");

请注意\\w匹配Unicode字母和下划线。 如果您不需要该行为(并且只需要匹配英文字母),请使用

string output = Regex.Replace(pathFOSE, @"(?i)(?<=[a-z0-9])\r\n(?=[a-z0-9])", " ");

如果你有各种操作系统或程序的换行符,你可以使用

string output = Regex.Replace(pathFOSE, @"(?i)(?<=[a-z0-9])(?:\r\n|\n|\r)(?=[a-z0-9])", " ");

如果有多个换行符,请添加+量词(?:\\r\\n|\\n|\\r)+

要对文件内容执行搜索和替换,您需要读取文件。

你可以做到

var pathFOSE = @"D:\Public\temp\FOSEtest.txt";
var contents = File.ReadAllText(pathFOSE);
var output = Regex.Replace(contents, @"(?i)(?<=[a-z0-9])(?:\r\n|\n|\r)(?=[a-z0-9])", " ");

var pathNewFOSE = @"D:\Public\temp\NewFOSE.txt";
if (!System.IO.File.Exists(pathNewFOSE))
{
    File.WriteAllText(pathNewFOSE, output);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM