2012-09-20 37 views
0

我已经阅读了一个html文件作为字符串builder.Now我想要在h1,h2和h3之间放置锚标签并给出不同的id和href链接。那么我怎么能做到这一点。我想要做下面的事情。 我试过Sb.Replace("<h1>", "<h1> <a id=1>");,但我不能给uniqe Id锚标签。所以我怎么读取所有h1,h2和h3,并把锚标签,并给锚标签唯一的id。StringBuilder查找字符串读取和替换

+0

你不能在一击中做到这一点。使用RegEx可能会更好,然后一次更换1并递增您的ID。 – lahsrah

+0

谢谢,但我怎样才能找到从stringbuilder的所有h1,h2和h3? – Hitesh

+2

[HtmlAgilityPack](http://htmlagilitypack.codeplex.com/) –

回答

1

您可以在System.Text.RegularExpressions名称空间中调用Regex.Replace,并在您分配新ID的位置定义一个自定义MatchEvaluator回调。

类似以下内容:

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; 
    } 
} 
+0

谢谢你的回复它的工作正常,但我怎样才能给每个锚标签唯一的ID。 – Hitesh

+0

ID的格式是什么? –

+0

现在我想锚点id不同然后使用int变量。我想要锚点的id如下:例如:

测试

所以我想要类似

Test

。简而言之,我的锚点ID将是我的内容之间h1,h2和h3 tag.Thanks – Hitesh