9.1.5 匹配单个匹配项

  Regex类的Match()方法可以在输入字符串中、根据给定的正则表达式找到匹配项,并把找到的匹配项作为单个匹配项返回。其中,每一个匹配项都为Match类型。

  Match类表示单个正则表达式匹配的结果,它包含两个属性和两个方法。其中,Empty属性表示空组、  Groups属性表示匹配的组的集合、NextMatch()方法获取从当前匹配结束位置开始的下一个匹配结果、Result  ()方法返回已传递的替换模式的扩展。

Regex类的Match()方法存在如下5种重载方法。

1Regex.Match(string input)

2Regex.Match(string input,int startat)

3Regex.Match(string input,string pattern)

4Regex.Match(string input,int beginning,int length)

5Regex.Match(string input,string pattern,RegexOptions options)

  其中,input参数指定输入字符串;pattern参数指定正则表达式;startat参数指定开始搜索的字符位置;  options参数指定匹配选项;beginning参数指定在输入字符串中开始搜索的字符位置;length参数指定子字符串中包含在搜索中的字符数。

  下面的代码在字符串“0123456789”中查找正则表达式“/d+”的匹配项。其中,RegexMatch()方法使用Regex类的Match()静态方法;Match()方法创建一个Regex实例regex,并使用该实例的Match()实例方法。

/// <summary>

/// 匹配给定的表达式

/// </summary>

/// <returns></returns>

private string RegexMatch()

{

string input = "0123456789";

string pattern = @"/d+";

Match match = Regex.Match(input,pattern);

if(match != null){return match.Value;}

return string.Empty;

}

/// <summary>

/// 匹配给定的表达式

/// </summary>

/// <returns></returns>

private string Match()

{

string input = "0123456789";

string pattern = @"/d+";

Regex regex = new Regex(pattern);

Match match = regex.Match(input);

if(match != null){return match.Value;}

return string.Empty;

}

  下面的代码在字符串“ABCDEFG”中查找正则表达式“[a-z]+”的匹配项。另外,在查找过程中启用了RegexOptions.IgnoreCase选项。其中,RegexMatchOptions()方法使用Regex类的Match()静态方法;MatchOptions()方法创建一个Regex实例regex,并使用该实例的Match()实例方法。

/// <summary>

/// 匹配给定的表达式,并带有选项

/// </summary>

/// <returns></returns>

private string RegexMatchOptions()

{

string input = "ABCDEFG";

string pattern = @"[a-z]+";

Match match = Regex.Match(input,pattern,RegexOptions.IgnoreCase);

if(match != null){return match.Value;}

return string.Empty;

}

/// <summary>

/// 匹配给定的表达式,并带有选项

/// </summary>

/// <returns></returns>

private string MatchOptions()

{

string input = "ABCDEFG";

string pattern = @"[a-z]+";

Regex regex = new Regex(pattern,RegexOptions.IgnoreCase);

Match match = regex.Match(input);

if(match != null){return match.Value;}

return string.Empty;

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值