[英]Regex - Replace text in HTML string when not contained within HTML tags
我希望有人可以幫助解決這個小問題。
我有一個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>
例如,我想用下面的跨度字符串替換單詞“ 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>
我只希望替換出現在“>”和“ <”之間的文本的原因是,因為我不希望HTML通過替換“ 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
更改為><
的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.