2012-12-15 35 views
1

這基本上是我的previous question的後續行動。我一直在使用這種代碼替換包含在一個字符串數組:優化正則表達式在for循環中替換?

string[] replacements = {"these", 
         "words", 
         "will", 
         "get", 
         "replaced"}; 

string newString = "Hello.replacedthesewordswillgetreplacedreplaced"; 

for (int j = 0; j < replacements.Length; j++) 
{ 
    newString = Regex.Replace(newBase, 
    @"((?<firstMatch>(" + replacements[j] + @"))(\k<firstMatch>)*)", 
    m => "[" + j + "," + (m.Groups[3].Captures.Count + 1) + "]"); 
} 

運行此代碼後newString將是:

你好[4,1] [0,1] [1 ,1] [2,1] [3,1] [4,2]

這適用於像上面那樣的小替換。它基本上可以立即替換字符串 - 但是對於大量的替換,它往往會減慢速度。

任何人都可以看到一種方式,我可以優化它,所以它取代更快?

我假設for循環是什麼放慢了速度。總是有一些字符串包含在數組中,不需要替換(因爲它們不包含在主要的newString字符串中),所以我想知道是否有方法在for循環之前檢查它。這可能會變慢,但...

我想不出一個更好的方式來做到這一點,所以我想我會問。謝謝你們的幫助! :)

回答

1

一些方法來嘗試(NB都未經測試,但我相信他們應該工作,並且比您當前的代碼更快)。

一個使用靜態編譯的正則表達式:

private static readonly Dictionary<string, int> Indexes = new Dictionary<string, int> 
{ 
    { "these", 0 }, 
    { "words", 1 }, 
    { "will", 2 }, 
    { "be", 3 }, 
    { "replaced", 4 }, 
}; 

private static readonly Regex ReplacementRegex = new Regex(string.Join("|", Indexes.Keys), RegexOptions.Compiled) 

... 
var occurrences = Indexes.Keys.ToDictionary(k => k, k => 0); 
return ReplacementRegex.Replace(newString, m => { 
    var count = occurences[m.Value]; 
    occurences[m.Value] = count + 1; 
    return "[" + Indexes[m.Value] + "," + count + "]"; 
});  

而且沒有一個正則表達式:

for (int j = 0; j < replacements.Length; j++) 
{ 
    var index = 0; 
    var count = 0; 
    var replacement = replacements[j]; 
    while((index = newString.IndexOf(replacement, index)) > -1) 
    { 
    count++; 
    newString = newString.Substring(0, index) + "[" + j + "," + count + "]" + newString.Substring(index + replacement.Length); 
    } 
} 
+0

非常感謝這個!雖然對於非正則表達式代碼有點麻煩。 「Hello.replacedthesewordswillgetrerecedreplaced」應該被替換成'你好。[4,1] [0,1] [1,1] [2,1] [3,1] [4,2]'但它變成了'你好,[4,1] [0,1] [1,1] [2,1] [3,1] [4,2] [4,3]'。第二部分應該是被替換的匹配附近字符串的數量。這是我在問我以前的問題時遇到的麻煩,但肯德爾弗雷和肖恩解決了這個問題。任何想法,我會如何得到這個工作?再次感謝豐富。 –