MatchCollection mc; String[] results = new String[20]; int[] matchposition = new int[20];
// Create a new Regex object and define the regular expression. Regex r = new Regex("abc"); // Use the Matches method to find all matches in the input string. mc = r.Matches("123abc4abcd"); // Loop through the match collection to retrieve all // matches and positions. for (int i = 0; i < mc.Count; i++) { // Add the match string to the string array. results[i] = mc[i].Value; // Record the character position where the match was found. matchposition[i] = mc[i].Index; }
MatchCollection 类表示成功的非重叠匹配的序列。该集合为不可变(只读)的,并且没有公共构造函数。MatchCollection 的实例是由 Regex.Matches 属性返回的。
以下示例使用 Regex 类的 Matches 方法,通过在输入字符串中找到的所有匹配填充 MatchCollection。该示例将此集合复制到一个字符串数组和一个整数数组中,其中字符串数组用以保存每个匹配项,整数数组用以指示每个匹配项的位置。
String[] results = new String[20];
int[] matchposition = new int[20];
// Create a new Regex object and define the regular expression.
Regex r = new Regex("abc");
// Use the Matches method to find all matches in the input string.
mc = r.Matches("123abc4abcd");
// Loop through the match collection to retrieve all
// matches and positions.
for (int i = 0; i < mc.Count; i++)
{
// Add the match string to the string array.
results[i] = mc[i].Value;
// Record the character position where the match was found.
matchposition[i] = mc[i].Index;
}