1

这基本上是我之前的问题的后续。我一直在使用这段代码来替换数组中包含的字符串:

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 循环之前检查它。不过,这可能会变得更慢......

我想不出更好的方法来做到这一点,所以我想我会问。谢谢你们的帮助!:)

4

1 回答 1

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);
  }
}
于 2012-12-15T15:32:03.090 回答