9.1.6 匹配多个匹配项

本文介绍如何使用C#中的Regex类进行正则表达式的匹配操作。通过两种方法演示了如何在字符串中查找符合特定模式的子串:一种是直接使用Regex类的静态方法Matches(),另一种是创建Regex实例并调用其Matches()方法。此外,还展示了如何使用RegexOptions来改变匹配行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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;
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值