加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Match类和MatchCollection类

发布时间:2020-12-14 01:38:39 所属栏目:百科 来源:网络整理
导读:《C#字符串与正则表达式参考手册》学习笔记之Match类和MatchCollection类 利用 Match 类和 MatchCollection 类,可以获得通过一个正则表达式实现的每一个匹配的细节。Match表示一次匹配,而 MatchCollection 类是一个 Match对象的集合 , 其中的每一个对象都

《C#字符串与正则表达式参考手册》学习笔记之Match类和MatchCollection类


利用Match类和MatchCollection类,可以获得通过一个正则表达式实现的每一个匹配的细节。Match表示一次匹配,而MatchCollection类是一个Match对象的集合其中的每一个对象都表示了一次成功的匹配。

我们可以使用Regex对象的Match()方法和Matches()方法来检索匹配。

1.Match()方法

前三种方法是实例方法,后两种是静态方法,所有方法都返回一个Match对象,其中包含了匹配的各种细节!注意:Match()对象只代表实现的第一次匹配,而不是所有的匹配!区别于Matches()!


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Regular
{
    class Program
    {
        static void Main(string[] args)
        {
            string inStr = "sea sem seg,word,love,sed";
            Regex myRegex=new Regex("se.");
            Match myMatch = myRegex.Match(inStr,4);

            while (myMatch.Success)
            {
                //MessageBox.Show(myMatch.Value);
                Console.WriteLine(myMatch.Value);
                myMatch = myMatch.NextMatch();
            }
             Console.ReadKey();
        }
    }
}

2.MatchCollection()方法

使用Regex.Matches()方法,可以得到MathCollection对象的一个引用。这个集合类中包含分别代表每一次正则表达式匹配的Match对象。在处理多匹配时尤其有用,而且可以代替Match.NextMatch()方法。

MatchCollection类有两个有用的属性CountItem。Count返回匹配的次数,Item允许通过下表访问每一个Match对象!

//
//                       _oo0oo_
//                      o8888888o
//                      88" . "88
//                      (| -_- |)
//                      0  =  /0
//                    ___/`---'___
//                  .' |     |// '.
//                 / |||  :  |||// 
//                / _||||| -:- |||||- 
//               |   |   -  /// |   |
//               | _|  ''---/''  |_/ |
//                 .-__  '-'  ___/-. /
//             ___'. .'  /--.--  `. .'___
//          ."" '<  `.____<|>_/___.' >' "".
//         | | :  `- `.;` _ /`;.`/ - ` : | |
//            `_.   _ __ /__ _/   .-` /  /
//     =====`-.____`.___ _____/___.-`___.-'=====
//                       `=---='
//
//
//     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//               佛祖保佑         永无BUG
//
//

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读