我已经阅读了一个html文件作为字符串builder.Now我想要在h1,h2和h3之间放置锚标签并给出不同的id和href链接。那么我怎么能做到这一点。我想要做下面的事情。 我试过Sb.Replace("<h1>", "<h1> <a id=1>");
,但我不能给uniqe Id锚标签。所以我怎么读取所有h1,h2和h3,并把锚标签,并给锚标签唯一的id。StringBuilder查找字符串读取和替换
0
A
回答
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;
}
}
相关问题
- 1. 用StringBuilder替换字符串?
- 2. 查找和替换c字符串
- 3. 字符串查找和替换
- 4. PHP查找和字符串替换后?
- 5. 字符串查找和替换方法
- 6. 字符串类替换和StringBuilder的替代
- 7. 在StringBuilder中替换字符
- 8. 查找和文件替换而不读取文件作为一个字符串
- 9. StringBuilder - 读取N个字符
- 10. 查找前后替换字符串
- 11. 查找并替换多行字符串
- 12. 查找并替换sed的字符串
- 13. 查找并替换HEX字符串
- 14. 查找并替换国家字符串
- 15. 查找并替换字符串错误
- 16. 查找并替换为字符串ArrayList
- 17. 查找字符串替换的Java
- 18. php替换字符串并读取完整字符串
- 19. StringBuilder和字符串相等性检查
- 20. Python中找到字符串和替换
- 21. 查找和替换字符串转换成路径批量
- 22. 查找并用子字符串结果替换字符串
- 23. 查找子字符串,根据情况替换子字符串
- 24. django模板,查找字符串替换为其他字符串
- 25. 的bash脚本:查找和替换字符串多字
- 26. 在Javascript中查找和替换字符
- 27. 查找和替换字符的想法
- 28. 如何查找和替换字符串中的src和href?
- 29. 获取字符串替换
- 30. 从文件中读取字符串后替换字符java
你不能在一击中做到这一点。使用RegEx可能会更好,然后一次更换1并递增您的ID。 – lahsrah
谢谢,但我怎样才能找到从stringbuilder的所有h1,h2和h3? – Hitesh
[HtmlAgilityPack](http://htmlagilitypack.codeplex.com/) –