Regex.Matches Method

 

Regex.Matches 有五種多載方法

 

一、MatchCollection Matches(string input)

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string pattern = @"(\d{3})-(\d{3}-\d{4})";
            string input = "212-555-6666 906-932-1111 415-222-3333 425-888-9999";

            Regex regex = new Regex(pattern);
            MatchCollection matches = regex.Matches(input);

            foreach (Match match in matches)
            {
                Console.WriteLine("Area Code:        {0}", match.Groups[1].Value);
                Console.WriteLine("Telephone number: {0}", match.Groups[2].Value);
                Console.WriteLine();
            }
        }
    }
}

結果為

 

二、MatchCollection Matches(string input, int startat)

Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string.

 

三、static MatchCollection Matches(string input, string pattern)

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string pattern = @"(\d{3})-(\d{3}-\d{4})";
            string input = "212-555-6666 906-932-1111 415-222-3333 425-888-9999";
            MatchCollection matches = Regex.Matches(input, pattern);

            foreach (Match match in matches)
            {
                Console.WriteLine("Area Code:        {0}", match.Groups[1].Value);
                Console.WriteLine("Telephone number: {0}", match.Groups[2].Value);
                Console.WriteLine();
            }
        }
    }
}

結果為

說明:

Regex.Matches 方法所回傳的值為一個 collection,

他是多個 Match object 的一個集合體。

 

四、static MatchCollection Matches(string input, string pattern, RegexOptions options)

Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.

 

五、static MatchCollection Matches(string input, string pattern, RegexOptions options, TimeSpan matchTimeout)

Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.