Regex类的Matches()方法可以在输入字符串中、根据给定的正则表达式找到匹配项,并把找到的匹配项作为单个匹配项返回。其中,每一个匹配项也都为Match类型。Regex类的Matches()方法存在如下4种重载方法。
(1)Regex.Matches(string input);
(2)Regex.Matches(string input, int startat);
(3)Regex.Matches(string input,string pattern);
(4)Regex.Matches(string input,string pattern,RegexOptions options)。
其中,input参数指定输入字符串;pattern参数指定正则表达式;startat参数指定开始搜索的字符位置;options参数指定匹配选项。
下面的代码在字符串“0123456789abcd321bfr987”中查找正则表达式“/d+”的匹配项。其中,RegexMatches()方法使用Regex类的Matches()静态方法;Matches()方法创建一个Regex实例regex,并使用该实例的Matches()实例方法。
/// <summary>
/// 匹配给定的表达式
/// </summary>
/// <returns></returns>
private string[] RegexMatches()
{
string input = "0123456789abcd321bfr987";
string pattern = @"/d+";
MatchCollection matches = Regex.Matches(input,pattern);
if(matches == null) return null;
string[] result = new string[matches.Count];
for(int i = 0; i < result.Length; i++)
{
result[i] = matches[i].Value;
}
return result;
}
/// <summary>
/// 匹配给定的表达式
/// </summary>
/// <returns></returns>
private string[] Matches()
{
string input = "0123456789abcd321bfr987";
string pattern = @"/d+";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(input);
if(matches == null) return null;
string[] result = new string[matches.Count];
for(int i = 0; i < result.Length; i++)
{
result[i] = matches[i].Value;
}
return result;
}
下面的代码在字符串“abcdABCDedfgEDFGwyz”中查找正则表达式“[a-z]+”的匹配项。另外,在查找过程中启用了RegexOptions.IgnoreCase选项。其中,RegexMatches()方法使用Regex类的Matches()静态方法;Matches()方法创建一个Regex实例regex,并使用该实例的Matches()实例方法。
/// <summary>
/// 匹配给定的表达式,并带有选项
/// </summary>
/// <returns></returns>
private string[] RegexMatchesOptions()
{
string input = "abcdABCDedfgEDFGwyz";
string pattern = @"[a-z]+";
MatchCollection matches
= Regex.Matches(input,pattern,RegexOptions.IgnoreCase);
if(matches == null) return null;
string[] result = new string[matches.Count];
for(int i = 0; i < result.Length; i++)
{
result[i] = matches[i].Value;
}
return result;
}
/// <summary>
/// 匹配给定的表达式,并带有选项
/// </summary>
/// <returns></returns>
private string[] MatchesOptions()
{
string input = "abcdABCDedfgEDFGwyz";
string pattern = @"[a-z]+";
Regex regex = new Regex(pattern,RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches(input);
if(matches == null) return null;
string[] result = new string[matches.Count];
for(int i = 0; i < result.Length; i++)
{
result[i] = matches[i].Value;
}
return result;
}
