将正则表达式模式应用于输入字符串所找到的成功匹配的集合

 

      先定义正则表达式,

         Regex itineraryRegex = new Regex(@"[""][sw|u4E00-u9FA5a-zA-Z:.,-:]+[""]");

       string  strline="字符串";

       //将匹配出满足条件的集合,以迭代方式
                   MatchCollection itineraryMcc = itineraryRegex.Matches(strline);

                    for (int i = 0; i < itineraryMcc.Count; i++)
                    {
                        string strResline = itineraryMcc[i].Value.Trim();//获取每一个的值
                    }

          集合是固定不变 (只读) 并且没有公共构造函数。 Regex.Matches 方法返回 MatchCollection 对象。

       集合包含零个或多System.Text.RegularExpressions.Match对象。如果匹配成功,将该集合填充与其中一个System.Text.RegularExpressions.Match对于每个输入字符串中找到的匹配项的对象。如果匹    配不成功,则集合中不包含System.Text.RegularExpressions.Match对象,并将其Count属性相等,则为零。

  将正则表达式模式应用于特定的输入字符串,正则表达式引擎使用两种技术之一来生成MatchCollection对象:

  • 直接计算。

    MatchCollection对象一次,填入到特定的调用导致的所有匹配项Regex.Matches方法。使用这一技术时的集合Count访问属性。它通常是填充集合的成本更高的方法,并需要更高的性能下降。

  • 迟缓计算。

    MatchCollection对象是否已填充根据需要在每个匹配的项。它等效于正则表达式引擎调用Regex.Match方法重复并将每个匹配项添加到集合。通过访问该集合时使用此方法,是其GetEnumerator方法中,或使用访问时foreach语句 (在 C#) 或For Each...Next语句 (在 Visual Basic 中)。

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"(?<word>w+)s+(k<word>)",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumped over the lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:
   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }

    }
原文地址:https://www.cnblogs.com/lwyu/p/5066312.html