正则表达式提取(三)

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace 正则表达式提取
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 提取字符串中的数字


            //string str = "大家好呀,hello,2010年10月10日是个好日子。恩,9494.吼吼!886";

            //////字符串提取的时候一般都不加^$
            //////Regex.Match()方法只能提取字符串中的一个匹配。
            ////一个Match对象,就表示一个匹配。
            ////Match match = Regex.Match(str, @"\d+");//这里需要写一个正则表达式,该正则表达式需要满足 “数字”

            //////.Value:输出匹配的结果
            ////Console.WriteLine(match.Value);

            ////Console.ReadKey();

            ////提取所有的匹配用Regex.Matches();

            ////返回值是所有的匹配项的集合。
            //MatchCollection matches = Regex.Matches(str, @"\d+"); //g
            //for (int i = 0; i < matches.Count; i++)
            //{
            //    if (matches[i].Success)
            //    {
            //        //输出每个匹配的值。
            //        Console.WriteLine(matches[i].Value);
            //    }
            //}
            //Console.ReadKey();



            #endregion

            #region 提取网页中的所有的Email地址

            //1.读取html文件中的所有的字符串
            string html = File.ReadAllText("1.htm");

            //    我的邮箱yzk@rupeng.com
            MatchCollection matches = Regex.Matches(html, @"([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9\-]+(\.[a-zA-Z]+){1,2})");
            int count = 0;
            for (int i = 0; i < matches.Count; i++)
            {
                if (matches[i].Success)
                {

                    //输出匹配的字符串(Email地址)
                    Console.WriteLine(matches[i].Value);


                    //Email的用户名:
                    Console.WriteLine(matches[i].Groups[1].Value);
                    //输出每个Email的域名
                    Console.WriteLine(matches[i].Groups[2].Value);
                    Console.WriteLine(matches[i].Groups[3].Value);
                    if (matches[i].Groups[2].Value.ToLower() == "gmail")
                    {
                        count++;
                    }
                }
            }

            //1.统计gmail的用户的个数
            //2.提取出每个Email的用户名。
            //提取组。
            Console.WriteLine("gmail的用户数为:{0},占{1}%", count, count / (double)matches.Count * 100);
            Console.WriteLine("共找到:{0}个。", matches.Count);
            Console.ReadKey();
            #endregion
        }
    }
}
原文地址:https://www.cnblogs.com/zpc870921/p/2640574.html