簡體   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