2009-05-28 102 views
0

你好,我有以下代碼與線C#正則表達式打破

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      string searchText = "find this text, and some other text"; 
      string replaceText = "replace with this text"; 


      String query = "%SystemDrive%"; 
      string str = Environment.ExpandEnvironmentVariables(query); 
      string filePath = (str + "mytestfile.xml"); 

      StreamReader reader = new StreamReader(filePath); 
      string content = reader.ReadToEnd(); 
      reader.Close(); 

      content = Regex.Replace(content, searchText, replaceText); 

      StreamWriter writer = new StreamWriter(filePath); 
      writer.Write(content); 
      writer.Close(); 
     } 
    } 
} 

替換沒有找到搜索文本,因爲它是在不同的行狀

發現這樣的文字,
和一些其他的文字。

我該如何編寫正則表達式epression,以便它能夠找到文本。

回答

1

你爲什麼試圖使用正則表達式進行簡單的搜索和替換?只需使用:

content.Replace(searchText,replaceText); 

你也可能需要添加「\ n」到您的字符串,以便添加換行符的更換相匹配。

嘗試改變搜索文本:

string searchText = "find this text,\n" + 
        "and some other text"; 
+0

我試圖執行這個方式,但我似乎仍不能替換的文本,如果我做了更換爲它工作 – 2009-05-28 16:08:01

+0

您需要在搜索文本添加換行符一行。嘗試逐字輸入搜索文本。我會編輯我的答案來向你展示。 – Stephan 2009-05-28 16:37:01

4

要搜索任何空格(空格,換行,製表符,......),你應該使用\ S在您的正則表達式:

string searchText = @"find\s+this\s+text,\s+and\s+some\s+other\s+text"; 

當然,這是一個非常有限的例子,但你明白了......

0

這是你的具體問題的一個附註,但你正在重新發明一些框架提供的功能f或者你。試試這個代碼:

static void Main(string[] args) 
{ 
    string searchText = "find this text, and some other text"; 
    string replaceText = "replace with this text"; 

    string root = Path.GetPathRoot(Environment.SystemDirectory); 
    string filePath = (root + "mytestfile.xml"); 

    string content = File.ReadAllText(filePath); 
    content = content.Replace(searchText, replaceText); 

    File.WriteAllText(filePath, content); 
}