Sử dụng MatchCollection & Match

Sử dụng phương thức Regex.Matches(...) để tìm kiếm tất cả các chuỗi con của một chuỗi, phù hợp với một biểu thức chính quy, phương thức này trả về một đối tượng MatchCollection.
** Regex.Matches() **
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public MatchCollection Matches(
    string input
)
 
public MatchCollection Matches(
    string input,
    int startat
)
 
public static MatchCollection Matches(
    string input,
    string pattern
)
 
public static MatchCollection Matches(
    string input,
    string pattern,
    RegexOptions options,
    TimeSpan matchTimeout
)
 
public static MatchCollection Matches(
    string input,
    string pattern,
    RegexOptions options
)
Ví dụ dưới đây, tách một chuỗi thành các chuỗi con, phân cách bởi các khoảng trắng (whitespace).
MatchCollectionExample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
 
namespace RegularExpressionTutorial
{
    class MatchCollectionExample
    {
        public static void Main(string[] args)
        {
 
            string TEXT = "This \t is a \t\t\t String";
 
            // \w : Ký tự chữ, viết ngắn gọn cho [a-zA-Z_0-9]
            // \w+ : Ký tự chữ, xuất hiện một hoặc nhiều lần.
            string regex = @"\w+";
 
 
            MatchCollection matchColl = Regex.Matches(TEXT, regex);
 
            foreach (Match match in matchColl)
            {
                Console.WriteLine(" ---------------- ");
                Console.WriteLine("Value: " + match.Value);
                Console.WriteLine("Index: " + match.Index);
                Console.WriteLine("Length: " + match.Length);
            }
 
 
            Console.Read();
        }
    }
 
}
Kết quả chạy ví dụ:

7- Nhóm (Group)

Một biểu thức chính quy bạn có thể tách ra thành các nhóm (group):
1
2
3
4
5