利用正则表达式提取html中的的Email地址

前端之家收集整理的这篇文章主要介绍了利用正则表达式提取html中的的Email地址前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Demo源码如下:

Demo下载地址:http://download.csdn.net/detail/zxcvbnm32123/5830571

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Text.RegularExpressions;
  7.  
  8. namespace _12提取html中的所有的Email地址
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. string html = File.ReadAllText("1.htm");
  15. //提取Email
  16. //通过()提取组,正则表达式如下
  17. string regEmail = @"([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9]+)(\.[a-zA-Z0-9])+";
  18. MatchCollection mc = Regex.Matches(html,regEmail);
  19. //请统计出常用邮件服务提供商的用户使用。
  20. //163
  21. //126
  22. //sohu
  23. //gmail
  24. //qq
  25. //sina
  26. //yahoo
  27. //hotmail
  28. int count_163 = 0;
  29. int count_126 = 0;
  30. int count_gmail = 0;
  31. int count_qq = 0;
  32. int count_sohu = 0;
  33. int count_sina = 0;
  34. int count_yahoo = 0;
  35. int count_hotmail = 0;
  36. foreach (Match match in mc)
  37. {
  38. #region MyRegion
  39. //match.Groups[0].Value中存储的值遇match.Value中存储的值是一样的
  40. //表示提取到的Email的完整字符串
  41. //match.Value
  42. Console.WriteLine(match.Value);
  43. switch (match.Groups[2].Value)
  44. {
  45. //default:
  46. }
  47. Console.WriteLine(match.Groups[0].Value);//0:完整邮箱名
  48. Console.WriteLine(match.Groups[1].Value);//:1:用户名
  49. Console.WriteLine(match.Groups[2].Value);//:2:域名
  50. Console.WriteLine(match.Groups[3].Value);//:3:组织名
  51. #endregion
  52.  
  53. Console.WriteLine(match.Value);//输出所有邮箱地址
  54. //通过match.Groups[]来获取提取组。注意:第0组存储的是完整匹配字符串,要获取组因该从索引1开始。
  55. switch (match.Groups[2].Value.ToLower())
  56. {
  57. case "163":
  58. count_163++;
  59. break;
  60. case "126":
  61. count_126++;
  62. break;
  63. case "gmail":
  64. count_gmail++;
  65. break;
  66. case "qq":
  67. count_qq++;
  68. break;
  69. case "sohu":
  70. count_sohu++;
  71. break;
  72. case "sina":
  73. count_sina++;
  74. break;
  75. case "yahoo":
  76. count_yahoo++;
  77. break;
  78. case "hotmail":
  79. count_hotmail++;
  80. break;
  81. }
  82. }
  83. Console.WriteLine("=============统计信息============");
  84. Console.WriteLine("邮箱总数:{0}",mc.Count);
  85. Console.WriteLine("网易163邮箱用户数:{0}",count_163);
  86. Console.WriteLine("网易126邮箱用户数:{0}",count_126);
  87. Console.WriteLine("gmail邮箱用户数:{0}",count_gmail);
  88. Console.WriteLine("QQ邮箱用户数:{0}",count_qq);
  89. Console.WriteLine("sohu邮箱用户数:{0}",count_sohu);
  90. Console.WriteLine("sina邮箱用户数:{0}",count_sina);
  91. Console.WriteLine("yahoo邮箱用户数:{0}",count_yahoo);
  92. Console.WriteLine("hotmail邮箱用户数:{0}",count_hotmail);
  93. Console.ReadKey();
  94. }
  95. }
  96. }

“1.htm”截图如下:



通过调试控制,查看获取的全部网页字符串,截图如下:


输出结果如下:



Demo下载地址:http://download.csdn.net/detail/zxcvbnm32123/5830571

猜你在找的正则表达式相关文章