c# – 查找并替换多个单词,而不会影响将来的替换

我想做的是某种“禁止的话”突出显示.

以下是我的价值观:

我有一个数组中的禁止词列表

{ "word1", "word2", "word3", "word4" }

我有一个表示评论的字符串

"i want to word1ban this word3 stupidword4 comment"

我想在html粗体标签(< b>< / b>)中突出显示这些内容.
例如,此注释字符串将变为:

"i want to <b>word1</b>ban this <b>word3</b> stupid<b>word4</b> comment"

我实际上这样做的方式是使用正则表达式替换它并且它工作得非常好,除了一件让我讨厌的事情.

foreach (var word in words)
{
    value = Regex.Replace(value, string.Format(@"{0}", Regex.Escape(HttpUtility.HtmlEncode(word))), "<b>" + word + "</b>", RegexOptions.IgnoreCase);
}

这个问题,也取决于数组中单词的顺序,是否有一个被禁止的单词会影响你的替换(< b>或< / b>)

例如,如果您将此添加到禁止的单词:< b 在代码之后,第一个迭代结果将是:

"i want to <b>word1</b>ban this <b>word3</b> stupid<b>word4</b> comment"

然后在&之后用< b替换:

"i want to <b><b</b>>word1</b>ban this <b><b</b>>word3</b> stupid<b><b</b>>word4</b> comment"

我不想影响我的替代品.我想知道我们怎么做到这一点.我尝试在我的正则表达式中添加例外以排除< b>和< / b>在替换中没有成功.

最佳答案 无视问题的整个“HTML”方面,只是从角度来看它

I want to find and replace several words, but I don’t want a replacement I’ve made to affect future replacements

你可以做一件事:立刻做所有替换!

var pattern = "(" + String.Join("|", words.Select(w => Regex.Escape(w))) + ")";
// e.g. (word1|word2|word3|word4)
value = Regex.Replace(
    value,
    pattern,
    "<b>$1</b>",
    RegexOptions.IgnoreCase);
点赞