正则表达式的应用

using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Net;

namespace 正则表达式
{
	class Program
	{
		static void Main(string[] args)
		{
			//正则表达式
			/*
			 * 元字符
			 .:b.g能匹配bug,big。。。。b..g能匹配biig,buug
			 []:b[aui]g能匹配bag,bug,big,b[0-9]g则能匹配0-9的任意字符,当.出现在[]中,不作为元字符
			 |:将两个匹配条件进行逻辑运算,或
			 ():将()之间括起来的表达式定义为组,并且将匹配到的表达式保存到临时区域,这个元字符在字符串提取时有用,
			    把一些字符表示为一个整体。改变优先级,定义提取组两个作用。
			 * :表示限定前面的表达式出现0次或多次,a*b-->aab,aaaab a.*b-->acb,adbdb,a(ab)*-->a,aab,aabab
			 +:匹配前面的子表达式一次或多次,9+-->9,99,999,zo+-->zo,zoo,不能匹配z
			 ?:匹配前面子表达式0次多次,do(es)?-->do,does 一般用来匹配可选部分
			 {n}:匹配确定的n次,zo(2)-->zoo,e{2}-->不能匹配,seed{e}可以匹配到
			 {n,}:至少匹配n次
			 {n,m}:至少匹配n次,最多m次
			 限定符:
			    
			 */

			//Regex.IsMatch();用来判断给定字符串是否匹配某个正则表达式
			//Regex.Match();用来从给定的字符串中按照正则表达式的要求提取【一个】匹配的字符串
			//Regex.Matches();用来从给定的字符串中按照正则表达式的要求提取【所有】匹配的字符串
			//Regex.Replace();替换所有正则表达式匹配的字符串为另一个字符串

			while (true)
			{


				string str = Console.ReadLine();
				//注意,要想完全匹配就必须加^和$,否则只要有字符串中含有匹配则返回true
				//验证邮政编码
				//bool b = Regex.IsMatch(str,"^[0-9]{6}$");

				//输入[10-25]任意数字
				//bool b = Regex.IsMatch(str,"^(1[0-9]|2[0-5])$");

				//验证手机号,\d为任意数字
				//bool b = Regex.IsMatch(str, @"^\d{11}$");

				//匹配z或者food
				//bool b = Regex.IsMatch(str,"z|food");

				//匹配身份证
				//长度为15或18位,首位不为0,15位时全部位数字,18位时最后一位为xX或者数字
				//写法1:^([1-9][0-9]{14}[0-9]{2}[0-9Xx])?$
				//写法2:^([1-9][0-9]{14}[1-9][0-9]{16}[0-9X])$
				//bool b = Regex.IsMatch(str,@"^([1-9][0-9]{14}[1-9][0-9]{16}[0-9X])$");

				//.net默认使用Unicode的匹配方式
				//bool b = Regex.IsMatch(str, @"\d+",RegexOptions.ECMAScript);
				//bool b = Regex.IsMatch(str,@"[0-9]+");//这个能准确判断是ASCII字符123,不包含Unicode字符123,其实就是输入法中的全角输出123
				//bool b = Regex.IsMatch(str,@"\w+",RegexOptions.ECMAScript);

				//判断字符串是否为国内电话,不考虑分机
				// 010-9999999,010xxxxxxx
				//0335-9999999,033599999999(区号+电话)
				//12306 5位
				//11位手机号
				//bool b = Regex.IsMatch(str,@"^(\d{3,4}-7\d{7,8}|\d{5})$");

				//匹配IP地址,4段用.分割的最多三位数字
				//bool b = Regex.IsMatch(str,@"^([0-9]{1,3}\.){3}[1-9]{1,3}$");

				//判断是否合法的日期格式“2008-08-08”
				//bool b = Regex.IsMatch(str,@"^[0-9]{4}-[0-9]{2}-[0-9]{2}$");
				//限制月份1-12
				//bool b = Regex.IsMatch(str,@"^[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}$");

				//判断是否是合法url地址
				//bool b = Regex.IsMatch(str,@"^[a-zA-z0-9]+://.+$");

				//提取字符串
				//一般提取不加^$
				//Regex.Match只提取一个匹配Regex.Mathces提取所有匹配
				//Match match = Regex.Match(str,"[0-9]+");
				//获取所有匹配项,提取html的网页邮箱
				//通过添加()就能实现提取组
				//在正则表达式中,()既有改变优先级的作用又具有提取组的功能
				//MatchCollection matcher = Regex.Matches(str, @"[-a-zA-Z_0-9.]+@[-a-zA-Z0-9_]+(\.[a-zA-Z]+)+");
				//foreach (Match item in matcher) {
				//item.Value表示本次提取到的字符串
				//item.Groups集合中存储的就是所有的分组信息
				//item.Groups[0].Value与item.vlaue是等价的都表示本次提取到的完整的字符串,表示整个邮箱字符串,而
				//item.Groups[i].Value则表示第一组的字符串
				//	Console.WriteLine(item.Value);
				//}

				//提取文件中的文件名
				//此处因为有“贪婪模式”的存在,所以\\肯定匹配最后一个\
				//string path = @"C:\DRIVERS\WIN\risfds.txt";
				//Match match = Regex.Match(path,@".+\\(.+)");
				
				//Console.WriteLine(match.Groups[1].Value);

				//从邮箱中提取用户名和后缀[email protected]
				Match match = Regex.Match(str,@"(.+)@(.+)");
				Console.WriteLine("{0},{1}",match.Groups[1].Value,match.Groups[2].Value);

				//从“192.168.10.5[prot=21,type=ftp]”这个字符串表示地址为192.168.10.5的服务21端口提供的是ftp服务
				//其中如果,type=ftp部分被省略,则默认为http服务
				Regex.Match(str,@"(.+)\[port=[0-9]{2,5}(,type=(.+))?\]");
				Console.WriteLine("ip:{0}",match.Groups[1].Value);
				Console.WriteLine("port:[0]",match.Groups[2].Value);
				Console.WriteLine(match.Groups[4].Value.Length != 0 ? match.Groups[3].Value : "http");
				//.+(贪婪模式)尽可能多的来匹配
				//当在“限定符”后使用?表示终止贪婪模式
				//终止贪婪模式,会尽可能少的匹配

				string msg = "abccccc";
				bool b = Regex.IsMatch(msg,@"^abc*?$");

				//下载字符串
				WebClient client = new WebClient();
				string html = client.DownloadString("http://localhost:8080");
				//从html字符串中提取邮件地址
				MatchCollection matcher = Regex.Matches(html,@"[-a-zA-Z0-9_.]+@[-a-zA-Z0-9]+(\.[a-zA-Z]+)(1,2)");
				foreach (Match item in matcher) {

					Console.WriteLine(item.Value);
				}
                                //提取网页图片
                WebClient wb = new WebClient();
                string html1 = wb.DownloadString("http://baidu.com");
                //提取image标签
                MatchCollection matcher1 = Regex.Matches(html1, @"<img\s+alt="""" src=""(.+)"" \>", RegexOptions.IgnoreCase);
                //通过提取组,获取img的src属性
                foreach (Match item in matcher1)
                {
                    string pathImg = "http://localhost:8080/" + item.Groups[1].Value;
                    wb.DownloadFile(pathImg, @"d:\" + System.DateTime.Now.ToFileTime());
                }

                //提取超链接
                WebClient wb2 = new WebClient();
                string html2 = wb.DownloadString("http://login");
                MatchCollection matches2 = Regex.Matches(html2,@"<a\s*href="".+?"">.+?</a>",RegexOptions.IgnoreCase);
                foreach (Match item in matches2) {
                    Console.WriteLine(item.Value);
                }

                //字符串替换
                string msg1 = "aaaabbbbasdf";
                msg1 = msg1.Replace("a","A");
                //替换转换的是格式
                msg1 = Regex.Replace(msg1,@"a+","A");

                //将hello 'welcome' to 'China'替换成 hello 【welcome】 to 【China】,如果替换成$1则"【$1】$$1"
                string msg2 = "hello 'welcome' to 'China'  'iss'   'is'";
                msg2 = Regex.Replace(msg2,"'(.+?)'","【$1】");

                //隐藏手机号码
                string msg3 = "架飞机离开38369331964发了卡经适房的";
                msg3 = Regex.Replace(msg,@"([0-9]{3})[0-9]{4}([0-9]{4})","$1****$2");

                //隐藏邮箱名
                string msg4 = "[email protected]";
                msg4 = Regex.Replace(msg4,@"\w+(@\w+\.\w+)","****$1",RegexOptions.ECMAScript);

                // \b表示单词的边界,单词便是[a-zA-z0-9]
                // \b是断言的一种,只是判断是否匹配并不真正匹配
                // \b表示一边是单词,一边是不是,不能两边都不是
                
                //将row的单词换成line
                msg = Regex.Replace(msg,@"\brow\b","line");

                //提取出3个字母的单词
                MatchCollection matches = Regex.Matches(msg,@"[a-z]{3}",RegexOptions.IgnoreCase);

                //JJJJ-->输出J
                msg = Regex.Replace(msg,@"(.)\1+","$1");

                        }
			 Console.ReadKey();
                     //敏感词过滤
            //用来储存需要审核的关键词
            StringBuilder sbMode = new StringBuilder();
            //用来储存绝对禁止的关键词
            StringBuilder sbBanned = new StringBuilder();
            string[] lines = File.ReadAllLines("1.txt");

            for (int i = 0;i < lines.Length;i++) {
                string[] parts = lines[i].Split('=');
                if (parts[1] == "{MOD}") {
                    sbMode.AppendFormat("{0}|", parts[0]);
                } else if (parts[1] == "{BANNED}") {
                    sbBanned.AppendFormat("{0}",parts[0]);
                }
            }
            sbMode.Remove(sbMode.Length - 1,1);
            sbBanned.Remove(sbBanned.Length - 1,1);

            string userInput = "";
            if (Regex.IsMatch(userInput, sbBanned.ToString())) {
                 
            } else if (Regex.IsMatch(userInput,sbMode.ToString())) {

            }

            //抓取网络招聘信息
            //信息头
            //<a href="http://" onclick="zzSearch.acStatRecJob(1);" class="jobname" target="_blank">项目经理</a>
            //
            WebClient wc = new WebClient();
            string html = wc.DownloadString("http://localhost.htm");
            MatchCollection match = Regex.Matches(html,"<a href=\"http://search.51job.com/job/46614662,c.html\" onclick=\"zzSearch.acStatRecJob(1);\" class=\"jobname\" target=\"_blank\">(.+?)</a>");
            foreach (Match item in match) {
                Console.WriteLine(item.Groups[1].Value);
            }
                     }

           }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章