正则表达式
注意:Regex并不是一个静态类。不过它有静态方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication8 { class Program { static void Main(string[] args) { string str = "123456"; Regex regex = new Regex(@"d{5}"); //这里使用它的非静态方法IsMatch bool b = regex.IsMatch(str); Console.WriteLine(b); //也可以直接调用它的静态方法IsMatch (注意:这个IsMatch方法与上面的那个IsMatch方法不是同一个方法) bool c = Regex.IsMatch(str,@"d{5}"); Console.ReadKey(); } } }
正则表达式元字符
.表示除n之外的任意的单个字符 a.b 就表示a与b中间除n外的任何单个字符都可以匹配。 []是一个字符组,我们要的值仅仅是这个字符组中的某一个字符。(注意:是单个字符) [0-9]就表示 匹配0到9之间的任何一个数字。 [a-z] 就表示:匹配a-z之间的任意一个字符。 [a-zA-Z] 表示配以匹配小写的a-z和大小的A-Z之间的任意一个字符(注意是一个字符) a[a-z][A-Z]b 这里使用了两个通配符,第一个通配符可以匹配小写的a-z之间的任意一个字符。第二个通配符可以通配A-Z之间的任意一个字符 [a-zA-Z0-9-] 它可以匹配a-z或A-Z或0-9直接的任意一个字符。 -表示也可以匹配一个- -前面加一个是转义的意思。因为-是一个连字符。所以这里需要将它转义一下
| 表示“或”的意思
限定符 ab[0-9]{3} 相当于 ab[0-9][0-9][0-9] 即:[]中括号这个表达式要出现3次 * 表示示前面的表达式出现0次或则多次。相当于{0,} 例如:颜色的英文,英国的写法和美国的写法都不同 英国的是colour 美国的是color ?还有另外一个意思。就是终止贪婪模式
==============^与$=========== ^还有一个意思,就是“非”的意思 $表示字符串的结束(其实就是正则表达式的结束) 678$ 表示字符串必须以8结尾,8前面必须紧跟着一个67。相当于(678)$ 。实际上就是表示字符串必须以678结尾
================简写============== 简写 s 表示所有空白符 w 表示[a-zA-Z0-9_] 由于.net默认采用unicode方式来匹配,所以w也可以匹配汉字
问:怎么匹配任意字符? 正则表达式的转义符 还有其他的如:* + . - {2,3} d 等等。 如果我要忽略所有的元字符。 例如 :我就想输出 * . - 这些字符串,而不是将他们作为有特殊意义的元字符怎么办呢?
一个正则表达式当出现双引号的时候我们怎么做书写//href="http://www.baidu.com" MatchCollection mcc = Regex.Matches(html,@"href=""http://www.baidu.com"""); //如果前面加了@符号,则遇到双引号的时候用两个双引号表示一个双引号 MatchCollection mccc = Regex.Matches(html,"href="http://www.baidu.com"");//如果前面没有加@符号,则遇到双引号的时候,需要用将双引号转义一下就可以了
单词的边界 注意:两个b中间是一个单词 但是 b###b 这两个b中就不是一个单词,因为它要求前面一个b的右边必须是组成单词的字符。 而b的右边是#,#不是组成单词的字符 而后面的那个b要求它左边必须是组成单词的字符,而后面这个b的左边也是# 它也不是组成单词的字符。所有 b###b 这两个b中间的并不是一个单词。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication9 { class Program { static void Main(string[] args) { //单词的边界b //单词边界就是指一个单词的左边和右边都是一些非单词的组成字符,如果 空格 .,? $^&* 等等 //下面有一段字符串,我们要将 row这个单词替换成line 这个单词 string str = "The day after tomorrow is my wedding day.The row we are looking for is .row. number 10."; //str = Regex.Replace(str,"row","line");//这是错误的,如果这样写的话,也会将tomorrow这个单词的最后的row也替换掉。因为tomorrow这个单词后面的三个字符tow不是一个独立的单词,所以这不符合我们的需求。我们的需求是将独立的单词row替换成line str = Regex.Replace(str,@"browb","line"); //两个b 的中间就是一个独立的单词 Console.WriteLine(str); //提取有三个字母的单词 string msg = "Hi,how are you?Welcome to our country!"; MatchCollection mc= Regex.Matches(msg,@"b[a-z]{3}b",RegexOptions.IgnoreCase); foreach (Match item in mc) { Console.WriteLine(item.Value); //输出:how are you our } Console.WriteLine("有三个字母的单词数量为{0}",mc.Count); //输出:有三个字母的单词数量为4 Console.ReadKey(); } } }
当正则表达式中需要括号嵌套的时候 如: (()()) 最外层的是第一个分组,里面的第一个是第二个分组,里面的第二个是第三个分组 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { string str = "张三253519939@qq.com大家好才是真的好"; //当正则表达式出现小括号套小括号的的时候,最外面的小括号是就Groups[1] 反正就是从外面往里面数,最外层是Groups[1] 然后依次挽后推 //例如: (()()) :最外面的小括号是Groups[1] 然后他们里面有两个小括号,前面那个就是Groups[2],后面那个就是Groups[3] MatchCollection mc = Regex.Matches(str,@"(([0-9]+)@[a-z]+.([a-z]+))"); foreach (Match item in mc) { Console.WriteLine(item.Groups[1].Value); //253519939@qq.com Console.WriteLine(item.Groups[2].Value);//253519939 Console.WriteLine(item.Groups[3].Value);//com } Match mt = Regex.Match(str,@"(([0-9]+)@[a-z]+.([a-z]+))"); Console.WriteLine(mt.Groups[1].Value);//253519939@qq.com Console.WriteLine(mt.Groups[2].Value);//253519939 Console.WriteLine(mt.Groups[3].Value);//com Console.ReadKey(); Match mt1 = Regex.Match(str,"[0-9]+@[a-z]+.[a-z]+",RegexOptions.IgnoreCase); Console.WriteLine(mt1.Groups[0].Value); } } }
基础:提取数据 using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { #region 案例1 while (true) { //要求用户输入一个整数,匹配是否为>=10 并且小于等于20的数 string s = Console.ReadLine(); bool b = Regex.IsMatch(s,"^(1[0-9]|20)$"); Console.WriteLine(b); } #endregion } } } namespace ConsoleApplication1 { class Program { static void Main(string[] args) { while (true) { Console.WriteLine("请输入一个字符串"); string s = Console.ReadLine(); bool b = Regex.IsMatch(s,"^z|food|do$"); //表示匹配以z或者food或者do开头,或者以z 或food 或do结尾的字符串 Console.WriteLine(b); } } } }验证邮政编码 (邮政编码是6个纯数字) namespace ConsoleApplication1 { class Program { static void Main(string[] args) { #region 验证邮政编码 while (true) { Console.WriteLine("请输入一个邮政编码"); string s2 = Console.ReadLine(); // bool b2= Regex.IsMatch(s2,"^[0-9]{6}$"); //或则采用下面的方式也可以 //由于.net默认采用unicode匹配方式,所以d也匹配全角的数字。 //RegexOptions.ECMAScript 表示安装ASCII的方式来匹配,所以如果输入全角的数字就无法匹配成功了 bool b2 = Regex.IsMatch(s2,@"^d{6}",RegexOptions.ECMAScript); Console.WriteLine(b2); //让我们来了解一下 "^[0-9]{6}$" 与 "[0-9]{6}"的区别 // "^[0-9]{6}$"只能匹配 0到9之间的任何6个数字。 //而 "[0-9]{6}" 一个字符串中只要包含连续6个0到9之间的数字 就能成功匹配 比如abc123555dcd 都可以匹配 } #endregion } } } 身份证验证 namespace ConsoleApplication1 { class Program { static void Main(string[] args) { #region 判断一个字符串是不是身份证号码 //1>长度为15位或者18为的字符串。首位不能是0 //2>如果是15位,则全部是数字 //3>如果是18位,则前17位都是数字,末尾可能是数字也可能是x或X while (true) { Console.WriteLine("请输入身份证号"); string s = Console.ReadLine(); bool b = Regex.IsMatch(s,"^[1-9][0-9]{14} |[1-9][0-9]{16}[0-9xX]$"); //或者用下面这种方式也可以,而且更高效。(尽量少用| 因为或涉及到效率的问题) bool Bb = Regex.IsMatch(s,"^[1-9][0-9]{14} ([0-9]{2}[0-9xX])?$"); Console.WriteLine(b); } #endregion } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { #region 贪婪模式 //什么是贪婪模式:比如:a{1,5} 表示可以匹配的a 最少一个,最多5个。 而贪婪模式就是尽可能多的去匹配,即按照最多的去匹配,那就按最多5个a去匹配。 //再例如:在正则中+ 这个限定符,表示:前面的表达式出现1次或者多次,那么按照贪婪模式,就是尽可能的多的找到前面的表达式,而不是仅仅是1个(当然:如果前面的表达式仅仅只能找到1个,就另说了)。 string str0 = "1111 。222221 11。"; //.+默认会按照贪婪模式来匹配:.可以表示所有的单个字符, 而+ 表示这个单个字符可以最少出现1次,最多不限制,那么就将这个str字符串全部匹配了 Match m0 = Regex.Match(str0,".+"); Console.WriteLine(m0.Value); //输出:1111 。222221 11。 //因为.可以匹配除n外的任何当个字符串,那么.+ 就表示这个“任何的单个字符”可以出现多次。于是.+就将str这个字符串全部匹配了。可以它发现后面还有个。号,如果.+将整个str字符串都匹配了,就没。号什么事了。加上这个。号就无法与str这个字符串匹配了。正则表达式就会尽量找到字符串与它来匹配,于是就会吐出一个字符,让.+只匹配1111 。222221 11 然后让正则的。号与str的。句号进行匹配。于是匹配成功了。 Match mm = Regex.Match(str0,".+。"); Console.WriteLine(mm.Value); //所以这个正则匹配的字符串就是1111 。222221 11。 #endregion #region 终止贪婪模式 //其实在限定符号前面加一个?号就是终止贪婪模式 string str = "1111 。222221 11。"; //.+默认是按贪婪模式来匹配,尽可能的多的去匹配。 //当在“限定符”后使用?号的时候,表示终止贪婪模式 //当终止贪婪模式以后,会尽可能少的去匹配 //现在在+后面加了一个?号。表示终止贪婪模式,+号表示前面的表达式出现1次或多次,既然现在是终止贪婪模式。于是会尽可能少的去匹配。于是就+?就表示前面的表达式出现1次。 //.号可以匹配所有单个字符。于是.匹配到了1 然后1出现1次 那么这里就提取到了一个1 Match m = Regex.Match(str,".+?"); Console.WriteLine(m.Value);//输出1 //.可以匹配所有单个字符,*号表示前面的表达式出现0次或多次,既然现在是终止贪婪模式。于是会尽可能少的去匹配。所以就*?就会往0个去匹配。即:.表示的任何单个字符出现0次。所以就什么也不会输出了 Match a = Regex.Match(str,".*?"); //这里什么也不会输出 Console.WriteLine(a.Value);//输出: 空 string msg = "abcccc"; //*表示前面的表达式出现0次或多次 *?表示终止贪婪模式。即b出现次。 所以这里提取到了一个a Match m1 = Regex.Match(msg,"ab*?"); Console.WriteLine(m1.Value);//输出:a //+表示前面的表达式出现1到多次 +?表示终止贪婪模式。那么前面的表达式就出现1次。 所以这里提取到abc Match m2 = Regex.Match(msg,"abc+?"); Console.WriteLine(m2.Value); // +表示前面的表达式最少出现1次或多次,+?表示终止贪婪模式,于是就会尽可能少的去匹配,.可以表示任何的单个字符。 //.+?。 如果1仅仅出现1次则不能匹配这个.+?。正则。只有1出现4次后面才开始出现一个。号 于是当1出现4次后,后面有一个句号于是与这个正则匹配成功。 所以这里提取到的是1111。 Match m3 = Regex.Match(str,".+?。"); Console.WriteLine(m3.Value);//输出:1111。 #endregion string str2 = "大家好,我是S.H.E。我是S。我是E。我是杨中科。我是苏坤。我是牛龙龙。我是N.L.L。ffff"; //Matches:在指定的输入字符串中搜索指定的正则表达式的所有匹配项。 //正则从“我是字符串开始,然后用小括号分组,小括号里面是一个.+ 表示可以匹配任何字符串,然后正则以。” MatchCollection m4 = Regex.Matches(str2,"我是(.+?)。"); foreach (Match item in m4) { Console.WriteLine(item.Groups[1].Value);//打印出S.H.E S H E 杨中科 苏坤 牛龙龙 N.L.L } Console.ReadKey(); } } }
提取网页中的邮箱 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { //下载字符串 WebClient client = new WebClient(); //提取http://bbs.rednet.cn/thread-44786545-1-1.html这个网页中的所有邮箱 string html = client.DownloadString("http://bbs.rednet.cn/thread-44786545-1-1.html"); MatchCollection mc = Regex.Matches(html,"mailto:(.+?)">"); foreach (Match item in mc) { Console.WriteLine(item.Groups[1].Value); } Console.ReadKey(); } } } 或者用这个正则也可以 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { //下载字符串 WebClient client = new WebClient(); //提取http://bbs.rednet.cn/thread-44786545-1-1.html这个网页中的所有邮箱 string html = client.DownloadString("http://bbs.rednet.cn/thread-44786545-1-1.html"); //MatchCollection mc = Regex.Matches(html,"mailto:(.+?)">"); MatchCollection mc = Regex.Matches(html,@"[a-zA-Z0-9-]+@[a-zA-Z0-9-]+(.[a-zA-Z0-9]+){1,2}"); foreach (Match item in mc) { Console.WriteLine(item.Value); //或者直接Console.WriteLine(item)也可以 } Console.ReadKey(); } } } 使用正则提取图片 | 使用WebClinet类来下载html 及下载图片 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { WebClient web = new WebClient(); //下载目标网页的html string html = web.DownloadString("http://bbs.rednet.cn/thread-43877250-1-1.html"); //<img style="cursor:pointer" id="aimg_6469251" aid="6469251" src="static/image/common/none.gif" onclick="zoom(this,this.getAttribute('zoomfile'),'1')" zoomfile="http://f3.rednet.cn/data/attachment/forum/201501/25/184529kl05irtsiqz0kgiu.jpg" file="http://f3.rednet.cn/data/attachment/forum/201501/25/184529kl05irtsiqz0kgiu.jpg.thumb.jpg" inpost="1" alt="234035xab04x994ix4htlx.jpg" title="234035xab04x994ix4htlx.jpg" onmouSEOver="showMenu({'ctrlid':this.id,'pos':'12'})" /> //提取图片地址 MatchCollection mc = Regex.Matches(html,@"<imgs+style="".+""s+id="".+"".+file=""(.+?)""",RegexOptions.IgnoreCase);//RegexOptions.IgnoreCase表示忽略大小写 foreach (Match item in mc) { Console.WriteLine(item.Groups[1].Value); //下载图片 web.DownloadFile(item.Groups[1].Value,@"d:123"+DateTime.Now.ToFileTime() + ".jpg"); } Console.ReadKey(); } } } 提取网页的内容的标题 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication7 { class Program { static void Main(string[] args) { WebClient web = new WebClient(); string html = web.DownloadString("http://search.51job.com/list/%2B,%2B,asp.net,1,%2B.html?lang=c&stype=2"); //<font color="#fe0201">ASP.NET</font>高级程序员</a> //<a title="ASP.NET工程师 (高薪诚聘)" target="_blank" MatchCollection mc = Regex.Matches(html,@"<as*title=""(.+?)""|<fonts+color="".+?"">(.+?)</font>(.+?)</a>"); List<string> list = new List<string>(); foreach (Match item in mc) { //list.Add(item.Groups[1].Value + item.Groups[2].Value); //Console.WriteLine(item.Groups[1].Value + item.Groups[2].Value); if (item.Groups[1].Value!=null && item.Groups[1].Value!="") { list.Add(item.Groups[1].Value); } else { list.Add(item.Groups[2].Value + item.Groups[3].Value); } } foreach (string item in list) { Console.WriteLine(item); } Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { //字符串替换 string msg = "你aaa好aa哈哈a你"; msg = msg.Replace("a","A");//将a替换成A Console.WriteLine(msg); //输出:你AAA好AA哈哈A你 //使用正则来替换 string msg1 = "你aaa好aa哈哈a你"; msg1 = Regex.Replace(msg,"a","A"); //将a替换成A Console.WriteLine(msg1);//输出:你AAA好AA哈哈A你 string msg2 = "你aaa好aa哈哈a你"; msg2 = Regex.Replace(msg2,"a+","A"); Console.WriteLine(msg2);//输出:你A好A哈哈A你 //将连续的_都替换成一个- string msg3 = "234____234__34_____55"; msg3 = Regex.Replace(msg3,"_+","-"); Console.WriteLine(msg3); //将hello 'welcome' to 'china' 替换成 hello 【welcome】 to 【china】 string msg4 = "hello 'welcome' to 'china'"; msg4 = Regex.Replace(msg4,@"s+'","【"); msg4 = Regex.Replace(msg4,"'s*","】"); Console.WriteLine(msg4); //第二种方式 string msg5 = "hello 'welcome' to 'china'"; msg5 = Regex.Replace(msg5,"'(.+?)'","【$1】"); Console.WriteLine(msg5); //将10/12/2015 这种日期转换成 2015-10-12 这种 string msg6 = "我的生日是10/12/2015椰"; msg6 = Regex.Replace(msg6,"([0-9]|1[0-2])/([0-9]|1[0-9]|2[0-9]|3[0-1])/([1-2][0-9]{3})","我的生日是$3-$1-$2椰"); Console.WriteLine(msg6); //输出:我们的我的生日是2015-10-12椰 //隐藏手机号码中的一些数字 string msg7 = "张三18620557713李四13655447569"; msg7 = Regex.Replace(msg7,@"(1[0-9]{2})[0-9]{4}([0-9]{4})","$1****$2"); Console.WriteLine(msg7);//输出:张三186****7713李四136****7569 Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication11 { class Program { static void Main(string[] args) { //叠词验证 string str = "简简单单清清白白千千万万曲曲弯弯"; //我们千万要注意:在正则表达式内部,必须使用来引用组。 比如在正则表达式内部1表示第一组 2表示第二组 3表示第三组 //在正则外部,比如使用替换的时候 是用$1来表示第一组 $2表示第二组,$3表示第三组 //看下面这个例子: @"(.)1+" 这个是一个正则表达式,在这里正则表示式的内部是用 1来引用了第一个分组, 而在这个正则的外部 我们用$1来表示一个分组的内容。 这都是正则表达式的规定 str = Regex.Replace(str,@"(.)1+","$1"); //这里@"(.)1+"是什么意思? 首先.表示除n外的任何单个字符,然后这个.用小括号括起来,就表示分组,而这个小括号后面跟的那个1是什么意思呢?其实这个1就表示这个分组本身的内容。 比如(.)表示字符"简"的时候 那么这个1就表示"简" 。 因为这里只有一个小括号,表示这个正则表达式只分了一组。所以这里这可以有一个1 如果分了2组,第二组就可以用2来表示。 //例如:()()12 此时这个1就表示前面那个括号的内容,2就表示后面那个括号的内容 //例如(()())123 因为这里分了3个组,第一个组就是最外面那个括号,他的内容就是1 最外面的那个括号里面有两个小括号,前面那个小2 即第二组,后面那个是3 即第三组 //例如: ((a)x(b))123 首先(a)x(b)是最外面的那个括号的内容,它表示第一组 (a)表示第二组 (b)表示第三组 // 而((a)x(b))后面跟了一个1 就表示这里出现一个第一组的内容 即axb后面又出现一个axb 即axbaxb 而1后面又出现一个2 而2的就表示第二组的内容 ,第二组的内容是a 即axbaxb后面要跟一个a 然后就组成了 axbaxba 然后2后面又跟了一个3 而3又表示第三组的内容,第三组的内容是b 所以axbaxba后面又出现一个b 然后就组成了 axbaxbab //AABB 这样的叠词 可以用 @"(.)1(.)2" 这个正则来提取,但是这样不是很严谨。因为AAAA 也能与这个正则匹配成功。虽然不严谨,但是可以用这个正则来提取叠词。 Console.WriteLine(str);//输出:简单清白千万弯曲 Console.ReadKey(); } } } 用正则将将一个邮箱的用户名的中间部分用*号替代 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ConsoleApplication12 { class Program { static void Main(string[] args) { string str = "你好,我的邮箱是:27006267@qq.com "; Match email = Regex.Match(str,"[0-9a-z_]+@[a-z0-9]+(.[a-z0-9]+){1,2}"); Program p=new Program(); Regex e = new Regex(".+"); //第一个参数是一个通过正则提取到的字符串,第二个参数是一个委托 str = e.Replace(email.Value,new MatchEvaluator(p.MatchE)); Console.WriteLine(str); Console.ReadKey(); } //这个match其实就是一个那个通过正则提取到的字符串27006267@qq.com 然后我们在里对这个字符串进行处理 public string MatchE(Match match) { string[] str = match.Value.Split('@'); string userName =str[0].Substring(1,str[0].Length-2); string newStr = null; for (int i = 0; i < userName.Length; i++) { newStr += "*"; } string firstStr = str[0].Substring(0,1); string lastStr = str[0].Substring(str[0].Length - 1,1); newStr = firstStr + newStr + lastStr + str[1]; return newStr; ; } } }
??
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |