2016-01-13 15 views
1

我剛寫了一個控制檯應用程序來替換大量utf-8編碼文件中的某個字符串。我需要覆蓋這個字符串的大約20個不同的情況,所以我將我的代碼片段減少到了必要的部分。 代碼看起來是這樣的:c#中字符串替換的最佳實踐

foreach (String file in allFIles) 
{ 
    string text = ""; 
    using (StreamReader r = new StreamReader(file)) 
    { 
     text = r.ReadToEnd(); 
    } 

    if (text.Contains(Case1)) 
    { 
     string textCase1 = ""; 
     using (StreamReader rCase1Reader = new StreamReader(file)) 
     { 
      textCase1 = rCase1Reader.ReadToEnd().Replace(Case1, Case1Const); 
     } 
     using (StreamWriter wCase1 = new StreamWriter(file, false, Encoding.UTF8)) 
     { 
      wCase1.Write(textCase1); 
     } 

     UsedFIles.Add(file); 
    } 
} 

我的問題是,如果我試圖替換字符串,看起來像這樣:"partnumber: 58"同時還有看起來一個字符串像這樣"partnumber: 585"

我的問題是,如果當前字符串包含所需的子字符串,並且還有一個類似於"partnumber: 58""partnumber: 585"的高度相似的字符串,那麼我的代碼也會替換高度相似的字符串。 有沒有辦法可以避免這種情況?

+6

使用正則表達式。粘貼一些文件的例子。 – BWA

+0

整個字符串是什麼樣的? – Liam

+1

您需要閱讀下一個字符。確定它是否是分隔符,然後決定是否要進行替換。 –

回答

0

使用正則表達式

new Regex(@"partnumber: 58$"); 
+1

爲什麼不使用'string.Replace'?正如詹姆斯巴拉斯評論的,如果這是一個共同的分隔符,那麼它可能更有效地使用 – Sayse

+4

該正則表達式將匹配58和585.這個問題明確地要避免這一點。 –

+1

這個正則表達式是錯誤的。一個會匹配兩個,另外兩個添加一個雙斜槓。 http://regexr.com/3cik8甚至刪除雙斜槓它不起作用http://regexr.com/3cikb – Liam

1

閱讀整個文件中,找到你感興趣的字符串,然後後檢查一下。假設文件有更多的閱讀。

foreach (String file in allFIles) 
    { 
     string text = ""; 
     using (StreamReader r = new StreamReader(file)) 
     { 
      text = r.ReadToEnd(); 
     } 

     int x = text.IndexOf(Case1); 
     while(x > -1) 
     { 
      if (text.Length - x > Case1.Length) 
      { 
       string nextBit = text.SubString(x + Case1.Length, 1); 
       if (IsDelimeter(nextBit)) 
       { 
        text = Replace(text, x, Case1, Case1Const); 
        x += Case1Const.Length; 
       } 
      } 
      else 
      { 
       text = Replace(text, x, Case1 Case1Const); 
       break; 
      } 
      x = text.IndexOf(Case1, x + 1); 
     } 

     File.WriteAllText(file, text); 
    } 
0

你可以嘗試:

var files = new[] { "File1.txt", "File2.txt", "File3.txt" }; 
// Where the key is the regex pattern to match and the value is the string to replace it with. 
var patterns = new Dictionary<string, string>() 
{ 
    { @"partnumber: \d\d", "FooBar" }, 
}; 

foreach(var file in files) 
{ 
    string str = File.ReadAllText(file); 
    foreach (var pattern in patterns) 
     str = Regex.Replace(str, pattern.Key, pattern.Value); 
    File.WriteAllText(file, str); 
} 

本例使用正則表達式(正則表達式),模式匹配partnumber: \d\d與啓動任何字符串「部分號碼:」和兩位數字結尾。正則表達式非常強大,你可以用它來描述你想要匹配的特定情況,所以你可以擴展這個多個模式。