簡體   English   中英

StringBuilder查找讀取並替換的字符串

[英]StringBuilder find string read and replace

我已經讀過一個html文件作為字符串生成器。現在我想將錨標記放在h1,h2和h3之間,並提供不同的id和href鏈接。 所以我該怎么做呢?我想做下面的事情。 我已經嘗試過Sb.Replace("<h1>", "<h1> <a id=1>"); 但是我不能給uniqe Id定位標記。因此,如何讀取所有h1,h2和h3並放置定位標記並為定位標記賦予唯一的ID。

您可以在System.Text.RegularExpressions命名空間中調用Regex.Replace並定義一個自定義MatchEvaluator回調,在其中分配新的ID。

類似於以下內容:

var regHeaders = new Regex(@"<(?<close>/)?h(?<header>\d)\s*>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var replaced = regHeaders.Replace(sb.ToString(), new MatchEvaluator(EvaluateHeaders));

並定義EvaluateHeaders回調,如下所示:

private static string EvaluateHeaders(Match m)
{
    bool closeTag = m.Groups["close"].Success;
    switch (int.Parse(m.Groups["header"].Value))
    {
        case 1: // h1
            return closeTag ? "</a></h1>" : "<h1><a href=\"header1\">Header1";
        // todo: your own implementation of the various other headers.
        default:
            return m.Value;
    }
}

編輯
根據您的最新評論,我將代碼更改為以下內容:

var regHeaders = new Regex(@"<h(?<header>\d)\s*>(?<content>.+?)</h\1>", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
var replaced = regHeaders.Replace(sb.ToString(), EvaluateHeaders);

private static string EvaluateHeaders(Match m)
{
    switch(int.Parse(m.Groups["header"].Value))
    {
        case 1: // <h1>content</h1>
            return string.Format("<h1><a href=\"#\" id=\"{0}\">{0}</a><h1>", m.Groups["content"].Value);
        default:
            return m.Value;
    }
}

暫無
暫無

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

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