我希望有人能帮助解决这个小问题。
我有一个 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>
我只想替换出现在“>”和“<”之间的文本的原因是我不希望通过替换“cellspacing”和“cellpadding”属性中的“in”一词来破坏 HTML。
如果使用正则表达式无法解决这个问题,我也愿意在 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))
最佳答案
如果您只想替换单词 in
排除包含“in”的单词,使用:
\bin\b
例如,http://gskinner.com/RegExr/?370qr
替换 ><
中的任何内容标签,无论是什么类型的标签,都试试这个
查找:
(<.*?>)(.*?)(</.*?>)
替换:
$1 YOUR_TEXT
3 美元
哪里YOUR_TEXT
就是你要改里面的内容><
到。
关于javascript - 正则表达式 - 替换 HTML 字符串中不包含在 HTML 标记中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19718639/