【问题标题】:Regex - Replace text in HTML string when not contained within HTML tags正则表达式 - 替换 HTML 字符串中不包含在 HTML 标记中的文本
【发布时间】:2013-10-31 23:53:55
【问题描述】:

我希望有人能帮助解决这个小问题。

我有一个 HTML 字符串,下面显示了一个简化的示例,我需要在其中查找和替换文本。但前提是该文本没有出现在 HTML 标记中,即“”。

<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
In this text I'd like to replace the word "in" with another piece of text instead.
</td>
</tr>
</table>

例如,我想用下面的 span 字符串替换单词“in”,从而得到下面的完整 HTML。

<span class="highlight">in</span>


<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<span class="highlight">In</span> this text I'd like to replace the word "<span class="highlight">in</span>" with another piece of text <span class="highlight">in</span>stead.
</td>
</tr>
</table>

我只希望替换出现在“>”和“

如果这不能使用正则表达式解决,我也愿意在 VB.NET、Javascript 或 JQuery 中解决。

提前感谢您提供的任何帮助!

解决了!

感谢 MiddleCSharp 的智慧

Dim rgx As New Regex(String.Format("\b{0}\b", SearchText, RegexOptions.IgnoreCase) 
ltrPageCopy.Text = rgx.Replace(HTMLText, String.Format("<span class=""highlight"">{0}</span>", SearchText))

【问题讨论】:

标签: javascript jquery html regex vb.net


【解决方案1】:

如果您只想替换单词in,不包括包含“in”的单词,请使用:

\bin\b

例如,http://gskinner.com/RegExr/?370qr

要替换 &gt;&lt; 标签内的任何内容,无论它是什么类型的标签,试试这个

查找:

(&lt;.*?&gt;)(.*?)(&lt;/.*?&gt;)

替换:

$1YOUR_TEXT$3

其中YOUR_TEXT 是您要将&gt;&lt; 中的内容更改为的内容。

这是演示http://regexr.com?370r1

【讨论】:

  • 您好,感谢您的快速回复。它可以是任何词,而不仅仅是“in”这个词,它取自用户的搜索词。我以“in”为例,因为在这种情况下这会严重破坏 HTML。干杯。
  • 感谢 MiddleCSharp!你最初的反应让我到了那里。这是我的最终代码。 Dim rgx As New Regex(String.Format("\b{0}\b", SearchText, RegexOptions.IgnoreCase) ltrPageCopy.Text = rgx.Replace(HTMLText, String.Format("{0}", SearchText))
  • \b 也匹配连字符 (-),因此该模式将匹配“内置”中的“in”。使用 /(^|\s)in(\s|$)/ 之类的东西可能会更好。
  • @user2943355 没问题,我已将初始响应添加回答案。
猜你喜欢
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多