C#解析单层html的中的文本,然后拼接起来

前端开发   发布日期:2025年05月14日   浏览次数:181

匹配单层html的小demo,应该能匹配大多数html字符串.多层(嵌套)html标签解析不出来.可能有小bug,我抛砖引玉下,哈哈.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. namespace ResolveHtmlText
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. string text = @"&nbsp;<span style='color:#1F497D'><span>y<span></span>&nbsp; &nbsp;<span style='color:#1F497D;'>1</span>&nbsp;<span style='color:#1F497D;background-color:#123456'>2</span><span style='color:#1F497D;background-color:#123456;text-align:center'>3</span> <span style='color:#1F497D;background-color:#123456;text-align:center;'>4</span> <span style='color:#1F497D;background-color:#123456;text-align:center;tt-l: 134;'>5</span>ggjf<a>123456</a>";
  14. Console.WriteLine("原字符串:" + text);
  15. text = text.Replace("\"", "'");
  16. text = text.Replace("&quot;", "'");
  17. text = text.Replace("&nbsp;", "");
  18. text = text.Replace("&lt;", "<");//将<的转义码&lt;都替换成<
  19. text = text.Replace("&gt;", ">");//将>的转义码&gt;都替换成>
  20. //string matchStr = @"<\s*[a-zA-Z0-9]+\s*>[^<^>]*<\s*/\s*[a-zA-Z0-9]+\s*>";
  21. string matchStr = @"<\s*[a-zA-Z0-9]+\s*[a-zA-Z]+\s*=\s*'\s*[a-zA-Z]"
  22. + @"+\s*:\s*[^<^>];?'\s*>[^<^>]"
  23. + @"*<\s*/\s*[a-zA-Z0-9]+\s*>|<\s*[a-zA-Z0-9]"
  24. + @"+\s*(\s*[a-zA-Z-]+\s*=\s*'(\s*[a-zA-Z-]+\s*:"
  25. + @"\s*[^:^;^<^>]+\s*;\s*)*(\s*[a-zA-Z-]+\s*:\s*"
  26. + @"[^:^;^<^>]+\s*)\s*;?\s*'\s*)*"
  27. + @"\s*>[^<^>]*<\s*/\s*[a-zA-Z0-9]+\s*>";
  28. Regex htmlReg = new Regex(matchStr);
  29. string result = null;
  30. MatchCollection htmlMatchCollection = htmlReg.Matches(text);
  31. StringBuilder sb = new StringBuilder();
  32. foreach (Match m in htmlMatchCollection)
  33. {
  34. if (m != null && m.Groups != null && m.Groups.Count > )
  35. {
  36. string temp = m.Groups[].Value;
  37. Console.WriteLine("临时值:" + temp);
  38. //Regex textReg1 = new Regex(@"[^<^>]+");
  39. //Match textMatch1 = textReg1.Match(temp);
  40. //if (textMatch1 != null && textMatch1.Groups != null && textMatch1.Groups.Count > 0)
  41. //{
  42. // result = textMatch1.Groups[0].Value;
  43. // sb.Append(result);
  44. //}
  45. Regex textReg = new Regex(@">.+<");
  46. Match textMatch = textReg.Match(temp);
  47. if (textMatch != null && textMatch.Groups != null && textMatch.Groups.Count > )
  48. {
  49. result = textMatch.Groups[].Value;
  50. if (result.Length > )
  51. {
  52. result = result.Substring(, result.Length - );
  53. sb.Append(result);
  54. }
  55. }
  56. }
  57. }
  58. Console.WriteLine("解析出的结果:" + sb.ToString());
  59. Console.ReadLine();
  60. }
  61. }
  62. }

 

以上就是C#解析单层html的中的文本,然后拼接起来的详细内容,更多关于C#解析单层html的中的文本,然后拼接起来的资料请关注九品源码其它相关文章!