在c#中使用正则表达式突出显示html中的单词

本文关键字:显示 html 单词 正则表达式 | 更新日期: 2023-09-27 18:04:01

我在stackoverflow上找到了这篇文章

在HTML中使用正则表达式&Javascript -差不多了

使用上面的文章,我试图用c#在服务器上突出显示HTML文本。代码如下所示:
string replacePattern = "$1<span style='"background-color:yellow'">$2</span>";
string searchPattern = String.Format("(?<=^|>)(.*?)({0})(?=.*?<|$)", searchString.Trim());
content = Regex.Replace(content, searchPattern, replacePattern, RegexOptions.IgnoreCase);

代码似乎工作得很好,除了当试图突出显示包含在图像源中的单词时:

搜索关键字:

ABC

搜索文本:

<div><img src="/site/folder/ABC.PNG" /><br />ABC</div>

结果将突出显示文本和图像名称。

在c#中使用正则表达式突出显示html中的单词

我将提供一个解决方案,但我同意仅仅使用Regex解析HTML最终可能不值得付出努力。也就是说,你比我们其他人更了解你的问题空间,所以如果你高亮显示的HTML在你的控制之下,你可能能够测试足够的域来实现你想要的正则表达式。

我的解决方案更改了您提供的正则表达式以采用这种方法:

  1. 匹配并捕获$1>字符,非贪婪捕获字符不在set [<>]
  2. 匹配并捕获您的关键字到$2
  3. 匹配并捕获到不在set [<>]中的$3非贪婪字符,加上<字符>

事项:

    格式良好的HTML效果最好,如果这个HTML是用户生成内容(UGC),那么,祝你好运,你应该使用HTML解析器:)
  1. 这将突出显示<textarea>...</textarea>
  2. 中的内容
  3. 这将突出显示<script>...</script>
  4. 中的内容

注意,您可以展开左侧的捕获来捕获标记名称,并且有条件地不替换一组标记,如textarea和script。

string searchString = "ABC";
string content = "<div><img src='/site/folder/ABC.PNG' /><br />ABC</div>";
string replacePattern = "$1<span style='"background-color:yellow'">$2</span>$3";
string searchPattern = String.Format("(>[^<>]*?)({0})([^<>]*?<)", searchString.Trim());
content = Regex.Replace(content, searchPattern, replacePattern, RegexOptions.IgnoreCase);
Console.WriteLine(content);