正则表达式:入门
正则表达式1适用对象.net framework提供的正则表达是专门服务于string类型的字符检索和模式匹配的,当然,string累提供的方法,比如IndexOf()等也能检索和匹配想要的方法,但是代码书写繁琐,方便性和灵活性上,都输于正则表达式。 2入门级的正则表达式2.1Plain-Text查找如下所示给出一串字符串:
要想检索出字符子串“ion”所在的所有位置,正则表达该如何书写呢?书写格式非常简单,如下所示: const string pattern = @"this";
然后利用.net提供的Regex类,匹配所有带有ion的位置,代码如下所示: MatchCollection myMatches = Regex.Matches(myText,pattern,RegexOptions.IgnoreCase |
RegexOptions.ExplicitCapture); //Mathes()匹配方法
foreach (Match nextMatch in myMatches)
{
Console.WriteLine(string.Format("{0} ",nextMatch.Index));
}
查询搜索后的结果为2个匹配项,index分别为0,181. myText的第0号位置为t,单词为this,第181号位置t,对应的单词也为this。
像pattern = “this”这种正则表达式,是一种文本模式,翻译过来称为 “plain -text search” 2.2metacharacters查找
例如1,想要查找以字母t开头的所有单词, const string pattern = @"bt";
MatchCollection myMatches = Regex.Matches(myText,RegexOptions.IgnoreCase |
RegexOptions.ExplicitCapture);
结果搜索到单词在myText中的index分别为0,51,153,181,205,230 const string pattern = @"ionb";
MatchCollection myMatches = Regex.Matches(myText,RegexOptions.IgnoreCase |
RegexOptions.ExplicitCapture);
结果搜索到单词在myText中的index分别为70,217,304都以ion结尾。常用的metacharacters主要包括:
以上元字符的任意组合查询举例: const string pattern = @"baS*ionb";
MatchCollection myMatches = Regex.Matches(myText,RegexOptions.IgnoreCase |
RegexOptions.ExplicitCapture);
结果,检索出的位置未334,可以看到时application这个单词。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |