2013-12-08 32 views
1

所以我需要執行多個正則表達式替換,我想知道這是否是不好的做法,因爲它可能會創建多個新字符串?有一個更好的方法嗎 ?多個正則表達式替換,它創建多個字符串?

var AllVariants = Regex.Replace(s, "5|S", "[5|S]"); 
AllVariants = Regex.Replace(AllVariants, "6|G", "[6|G]"); 
AllVariants = Regex.Replace(AllVariants, "8|B", "[8|B]"); 
AllVariants = Regex.Replace(AllVariants, "4|A", "[4|A]"); 
AllVariants = Regex.Replace(AllVariants, "1|I", "[1|I]"); 
AllVariants = Regex.Replace(AllVariants, "0|O", "[O|0]"); 
+0

考慮在switch語句和StringBuilder中使用簡單的循環遍歷你的字符串。創建一些額外的字符串並不重要,因爲垃圾收集器可以很好地處理它。但是,您的代碼多次遍歷字符串。 –

回答

0

您的方法存在的問題是您將瀏覽字符串6次,如果您將所有內容放在一個表達式中,您將只瀏覽一次該字符串。

string[] corr = {"[5|S]", "[6|G]", "[8|B]", "[4|A]", "[1|I]", "[0|O]"}; 

Regex reg = new Regex(@"([5S])|([6G])|([8B])|([4A])|([1I])|([0O])"); 

var AllVariants = reg.Replace(s, delegate(Match m) { 
    for (int key = 0; key < corr.Length; ++key) 
     if (string.IsNullOrEmpty(m.Groups[key+1].Value) == false) break; 
    return corr[key]; 
}); 
+0

嘿卡西米爾,我明白你說的沒錯。從你的回答中,我看不出替代品會如何給我最終結果。即如果我遇到字符「5」,我希望它被[5 | S]取代。我不明白你的答案是如何做到的? – StevieB

+0

@StevieB:對不起,我確信你想用'[5 | S]'替換字符串'5 | S''。在這種情況下,您需要使用matchevaluator委託。我會編輯我的答案。 –

+0

剛剛得到一個編譯錯誤,並不是所有的路徑都返回一個值 – StevieB