《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类有两个有用的属性Count和Item。Count返回匹配的次数,Item允许通过下表访问每一个Match对象!
- //
- // _oo0oo_
- // o8888888o
- // 88" . "88
- // (| -_- |)
- // 0\ = /0
- // ___/`---'\___
- // .' \\| |// '.
- // / \\||| : |||// \
- // / _||||| -:- |||||- \
- // | | \\\ - /// | |
- // | \_| ''\---/'' |_/ |
- // \ .-\__ '-' ___/-. /
- // ___'. .' /--.--\ `. .'___
- // ."" '< `.___\_<|>_/___.' >' "".
- // | | : `- \`.;`\ _ /`;.`/ - ` : | |
- // \ \ `_. \_ __\ /__ _/ .-` / /
- // =====`-.____`.___ \_____/___.-`___.-'=====
- // `=---='
- //
- //
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- //
- // 佛祖保佑 永无BUG
- //
- //