c# - 使用 regex.replace 替换 html 字符串中的单词而不影响 html 标签和部分单词
问题描述
我想用另一个单词替换 html 字符串中的单词,但它只能替换确切的单词,而不是它是单词部分拼写的一部分。我遇到的问题是 html 打开或关闭标签或其他 html 元素正在影响正则表达式中匹配的单词,或者它正在替换部分单词。
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>”;
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 ***  must go! </div><p>*** *** ***</p>
任何建议和帮助将不胜感激。
解决方案
这是我使用 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;
推荐阅读
- java - 为什么在 exec.shutdown() 之前使用 exec.isTerminated() 和 java 中的 ExecutorService?
- .net - 使用 DynamicResource 如何“神奇地”将画笔转换为颜色?
- javascript - 为什么 nodemailer 发送重复的电子邮件?
- ruby-on-rails - 构建 Dockerfile 时 RUN 不执行命令
- excel - 添加 MMYYYY 以将名称保存在变体上
- javascript - 如何修复“找不到变量:项目”
- excel - 使用 VBA 从整个工作表中删除小数
- java - 测试在 JUnit5 中不按指定顺序运行
- c# - linq C# 语句返回的匿名类型错误
- http - Angular 8 - 如何在 Angular HttpParams 中添加多个同名查询参数