9.1.5 匹配单个匹配项
来源:互联网 发布:b2b群发软件破解版 编辑:程序博客网 时间:2024/05/16 02:09
Regex类的Match()方法可以在输入字符串中、根据给定的正则表达式找到匹配项,并把找到的匹配项作为单个匹配项返回。其中,每一个匹配项都为Match类型。
Match类表示单个正则表达式匹配的结果,它包含两个属性和两个方法。其中,Empty属性表示空组、 Groups属性表示匹配的组的集合、NextMatch()方法获取从当前匹配结束位置开始的下一个匹配结果、Result ()方法返回已传递的替换模式的扩展。
Regex类的Match()方法存在如下5种重载方法。
(1)Regex.Match(string input);
(2)Regex.Match(string input,int startat);
(3)Regex.Match(string input,string pattern);
(4)Regex.Match(string input,int beginning,int length);
(5)Regex.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;
}
- 9.1.5 匹配单个匹配项
- 单个字符串匹配
- 9.1.6 匹配多个匹配项
- 正则表达式(一)-- 匹配单个字符
- JavaScript 中匹配单个字符实例
- 匹配.
- 匹配
- 匹配
- 匹配
- 匹配
- 匹配
- 匹配
- 正则表达式学习(四)匹配单个字符
- 正则表达式2——匹配单个字符
- [跟我学正则表达式] 2. 匹配单个字符
- 返回单个匹配结果 正则(PHP代码函数)
- 安卓的单个及多个搜索自动匹配
- 正则表达式学习(四)匹配单个字符
- 9.1.7 替换
- Java中assert的用法『转』
- 史上最简! IIS下安装PHP
- 9.1.6 匹配多个匹配项
- 随笔
- 9.1.5 匹配单个匹配项
- 9.1.4 检查是否匹配表达式
- 什么是序列化?
- js整理
- 总结加盟店骗人手段
- 9.1.3 正则表达式选项
- jQuery入门第一步
- AIX常用命令扫盲篇
- 9.1.2 正则表达式类Regex