资源描述:
《C#Regex深入正则表达式》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、C#Regex深入正则表达式匹配字符串——从一段数据中提取自己所需要的数据信息Regexregex=newRegex(正则表达式);Regexregex=newRegex(正则表达式,RegexOptions.None
2、RegexOptions.IgnoreCase
3、RegexOptions.Multiline);//None无;IgnoreCase能够在匹配是忽略大小写;Multiline调整^和$的意义,改为匹配一行的开头和结尾Matchm=regex.Match(内容字符串); //取一个符合条件的值Response.Writ
4、e(m.Value.ToString()); //获得结果Matchmatchs=regex.Matchs(内容字符串); //取多个符合条件的值(数组)foreach(Matchminatchs){ Response.Write(m.Value.ToString()); //遍历获取结果 }Response.Write(ms.Count); //数组长度-----------------------------------------------------------------
5、---------------组的概念——当获的数据信息是组结构时,可用它来获取Regexregex=newRegex(@"(d+)/(d+)");Matchmatchs=regex.Matches(@"最后比分是:19/24");foreach(Matchminmatchs){ foreach(stringnameinregex.GetGroupNames()) //组的概念 { Response.Write(("capturegroup"{0}"valueis:"{1}"",,name,m.Groups[nam
6、e].Value); }}输出:capturegroup"0"valueis:"19/24"capturegroup"1"valueis:"19"capturegroup"1"valueis:"24"附:用@"(?d+)/(?d+)"替代@"(d+)/(d+)"看看结果--------------------------------------------------------------------------------替换字符串Regexregex=newRegex(expression,o
7、ption);stringresult=regex.Replace(str1,str2);//str1为原字符串;str2为替换内容,它可以包含以下一些特殊字符串,用来代表特别意义$&匹配的字符串,也可以用$0$1,$2,...匹配字符串中的对应组,用索引标示${name}匹配字符串中的对应组,用名称标示$‘匹配位置之前的字符串$’匹配位置之后的字符串$$一个‘$’字符$_输入字符串$+匹配字符串的所有组中,最后一个组中的数据例1:Regexregex=newRegex(@"d+",RegexOptions.None);string
8、result=regex.Replace("fef12/21df33/14727/1","<<$&>>");功能:所有数字型的数据都被替换成了"<<数字>>"格式输出结果:fef<<12>>/<<21>>df<<33>>/<<14>><<727>>/<<1>>例2:Regexregex=newRegex(@"(d+)/(d+)",RegexOptions.None);stringresult=regex.Replace("fef12/21df33/14727/1","$+");功能:所有data1/data2匹配的数据,都被替换成
9、了data2输出结果:fef21df141例三:自定义转换公式把”Ihave200dollars”中间的money加倍usingSystem.Text.RegularExpressions;classRegularExpressions{ staticstringCapText(Matchm) { stringx=m.ToString(); stringresult=(int.Parse(x)*2).ToString(); returnresult; } staticvoidMai
10、n() { stringtext="ihave200dollars"; stringresult=Regex.Replace(text,@"d+",newMatchuator(Regula