C#程序中利用正则表达式对字符串分组并获取组值

 #region 匹配时设置 显示捕获 选项
        /// <summary>
        /// 匹配时设置 显示捕获 选项
        /// </summary>
        protected void test16()
        {       
            string pattern = @"(\d{3})";
            string str = "123a432";

            //匹配时设置为“ExplicitCapture”,将不捕获没有显式命名的组
            Regex reg = new Regex(pattern, RegexOptions.ExplicitCapture);

            if (reg.IsMatch(str))
            {
                Match match = reg.Match(str);

                GroupCollection coll = match.Groups;
                
                int i = 0;
                
                foreach (Group item in coll)
                {
                    Console.WriteLine("group" + i + ": " +item.ToString());
                    
                    //Console.WriteLine("group" + i + ": " + coll[i].Value.ToString());
                    i++;
                }

            }

        }
        #endregion

        #region 获取捕获的多个内容后,循环输出
        /// <summary>
        /// 获取捕获的多个内容后,循环输出
        /// </summary>
        protected void test17()
        {
            string pattern = @"a.*?b";
            string input = "aabaaaaaaaaaaab";

            Regex regex = new Regex(pattern);

            if (regex.IsMatch(input))
            {
                MatchCollection colls = Regex.Matches(input, pattern);

                foreach (Match item in colls)
                {
                    Console.WriteLine(item.Value.ToString());
                }
            }


        }
        #endregion

        #region 获取捕获的多个分组后,循环输出
        /// <summary>
        /// 获取捕获的多个分组后,循环输出
        /// </summary>
        protected void test18()
        {
            string pattern = @"(\d{3})(\w{2})";
            string input = "123ab";

            Regex regex = new Regex(pattern);

            if (regex.IsMatch(input))
            {
                GroupCollection colls = Regex.Match(input, pattern).Groups;

                Console.WriteLine(Regex.Match(input, pattern).Value);

                Console.WriteLine("---------------------");

                foreach (Group item in colls)
                {
                    Console.WriteLine(item.Value.ToString());
                }
            }


        }
        #endregion


 
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值