簡體   English   中英

使用正則表達式替換特定的HTML標簽

[英]Replacing specific HTML tags using Regex

好了,對您來說很簡單。 我們正在使用ActiveReport的RichTextBox來顯示一些隨機的HTML代碼。

可以在以下位置找到ActiveReport支持的HTML標記: http : //www.datadynamics.com/Help/ARNET3/ar3conSupportedHtmlTagsInRichText.html

我要執行的一個示例是將<div style="text-align:*</div>的任何匹配替換為<p style=\\"text-align:*</p>以便使用受支持的標簽用於文本對齊。

我發現以下正則表達式可以在我的html輸入中找到正確的匹配項:

<div style=\"text-align:(.*?)</div>

但是,我找不到在替換后將先前的文本保留在標簽中的方法。 任何線索? 是我還是Regex通常是PITA? :)

    private static readonly IDictionary<string, string> _replaceMap =
        new Dictionary<string, string>
            {
                {"<div style=\"text-align:(.*?)</div>", "<p style=\"text-align:(.*?)</p>"}
            };

    public static string FormatHtml(string html)
    {
        foreach(var pair in _replaceMap)
        {
            html = Regex.Replace(html, pair.Key, pair.Value);
        }

        return html;
    }

謝謝!

使用$1

{"<div style=\"text-align:(.*?)</div>", "<p style=\"text-align:$1</p>"}

請注意,您可以將其簡化為:

{"<div (style=\"text-align:(?:.*?))</div>", "<p $1</p>"}

與嘗試使用正則表達式解析HTML相比,使用像HtmlAgilityPack這樣的HTML解析器通常也是一個更好的主意。 這是你如何做到的:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
foreach (var e in doc.DocumentNode.Descendants("div"))
    e.Name = "p";
doc.Save(Console.Out);

結果:

<p style="text-align:center">foo</p><p style="text-align:center">bar</p>

而不是使用正則表達式,應使用更適合於解析和修改html的工具。 我會為此推薦Html Agility Pack-它是為滿足您的需要而編寫的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM