Match类和MatchCollection类

前端之家收集整理的这篇文章主要介绍了Match类和MatchCollection类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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


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

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

1.Match()方法

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


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8.  
  9. namespace Regular
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. string inStr = "sea sem seg,word,love,sed";
  16. Regex myRegex=new Regex("se.");
  17. Match myMatch = myRegex.Match(inStr,4);
  18.  
  19. while (myMatch.Success)
  20. {
  21. //MessageBox.Show(myMatch.Value);
  22. Console.WriteLine(myMatch.Value);
  23. myMatch = myMatch.NextMatch();
  24. }
  25. Console.ReadKey();
  26. }
  27. }
  28. }

2.MatchCollection()方法

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

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

  1. //
  2. // _oo0oo_
  3. // o8888888o
  4. // 88" . "88
  5. // (| -_- |)
  6. // 0\ = /0
  7. // ___/`---'\___
  8. // .' \\| |// '.
  9. // / \\||| : |||// \
  10. // / _||||| -:- |||||- \
  11. // | | \\\ - /// | |
  12. // | \_| ''\---/'' |_/ |
  13. // \ .-\__ '-' ___/-. /
  14. // ___'. .' /--.--\ `. .'___
  15. // ."" '< `.___\_<|>_/___.' >' "".
  16. // | | : `- \`.;`\ _ /`;.`/ - ` : | |
  17. // \ \ `_. \_ __\ /__ _/ .-` / /
  18. // =====`-.____`.___ \_____/___.-`___.-'=====
  19. // `=---='
  20. //
  21. //
  22. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  23. //
  24. // 佛祖保佑 永无BUG
  25. //
  26. //

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