首页 > 解决方案 > 使用 regex.replace 替换 html 字符串中的单词而不影响 html 标签和部分单词

问题描述

我想用另一个单词替换 html 字符串中的单词,但它只能替换确切的单词,而不是它是单词部分拼写的一部分。我遇到的问题是 html 打开或关闭标签或其他 html 元素正在影响正则表达式中匹配的单词,或者它正在替换部分单词。

PostTxt = “&lt;div>The <b>cat</b> sat on the mat, what a catastrophe.
 The <span>cat</span> is not allowed on the mat. This makes things complicated; the cat&nbsp must go! 
</div><p>cat cat cat</p>”; 

    string pattern = "cat";

    //replacement string to use
    string replacement = "******";

    //Replace words
    PostTxt = Regex.Replace(PostTxt, pattern, replacement, RegexOptions.IgnoreCase);
}

我希望它回来。

<div>The <b>***</b> sat on the mat, what a catastrophe. The <span>***</span> is not allowed on the mat. This makes things complicated; the ***&nbsp must go! </div><p>*** *** ***</p>

任何建议和帮助将不胜感激。

标签: c#htmlregexstringreplace

解决方案


这是我使用 html-agility-pack.net 实现的代码的简化解决方案。正则表达式不是解决此问题的方法,请参阅:为什么不能使用正则表达式来解析 HTML/XML:外行术语的正式解释。——奥利维尔·雅科特-德斯科姆

PostTxt = "<div>The <b>cat</b> sat on the mat, what a catastrophe.
 The <span>cat</span> is not allowed on the mat. This makes things complicated; the cat must go! 
</div><p>Cat cat cat</p>"; 
                
HtmlDocument mainDoc = new HtmlDocument();
mainDoc.LoadHtml(PostTxt);

//replacement string to use
string replacement = “*****”;

string pattern = @"\b" + Regex.Escape("cat") + @"\b";

var nodes = mainDoc.DocumentNode.SelectNodes("//*") ?? new HtmlNodeCollection(null);

foreach (var node in nodes)
{
    node.InnerHtml = Regex.Replace(node.InnerHtml, pattern, replacement, RegexOptions.IgnoreCase);
}

PostTxt = mainDoc.DocumentNode.OuterHtml;

推荐阅读