正则表达式
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.IO; namespace 正则表达式 { class Program { static void Main(string[] args) { char[] ch = { '.','[',']','-'}; string ze = @"\d,\D,\w,\w"; // X re = null; bool ok= Regex.IsMatch("bbbg", "^b.*g$"); Console.Write(ok); //匹配数字格式 Console.WriteLine( Regex.IsMatch("324622",@"^\d{6}$")); Console.WriteLine(Regex.IsMatch("324622", @"^[0-9]{6}$")); //匹配身份证号格式 Console.WriteLine(Regex.IsMatch("1234567890123222", @"^([0-9]{15}$|\d{18}$)")); //判断Email地址 string email = "98123@qq.com"; Console.WriteLine(Regex.IsMatch(email,@"^\w+@\w+\.\w+$")); //IP地址 Console.WriteLine(Regex.IsMatch("233.324.345.322", @"^\d{3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")); //匹配日期格式 //string data= Console.ReadLine(); //Console.WriteLine(Regex.IsMatch(data,@"^\d{4}\-\d{1,2}\-\d{1,2}$")); //字符串提取 Match math = Regex.Match("age=21",@"^(.+)=(.+)$"); //改变优先级 分组 if (math.Success) { Console.WriteLine(math.Groups[1].Value); Console.WriteLine(math.Groups[2].Value); } //()还能分组 math = Regex.Match("张国朋是大好人啊大好人zgp", @"^(\w+)(是大好人啊大好人)(\w+$)"); if (math.Success) { Console.WriteLine(math.Groups[1].Value); Console.WriteLine(math.Groups[2].Value); Console.WriteLine(math.Groups[3].Value); } math = Regex.Match("我是张国朋。我现。在很好。", @"^我是(\w+)"); if (math.Success) { Console.WriteLine(math.Groups[1].Value); } //贪婪模式 匹配到最后一个 math = Regex.Match("我是张国朋。我现。在很好。",@"^我是(.+)。"); if (math.Success) { Console.WriteLine(math.Groups[1].Value); } //加? 非贪婪模式 math = Regex.Match("我是张国朋。我现。在很好。", @"^我是(.+?)。"); if (math.Success) { Console.WriteLine(math.Groups[1].Value); } //得到字符串中所有的名字 string sre = "我是张国朋,他是黎明,我是范冰冰,我是刘德华,我怎么没有了?fyt"; math = Regex.Match(sre,@".是(.\w+?),"); if (math.Success) { Console.WriteLine(math.Groups[1].Value); Console.WriteLine(math.Groups[2].Value); Console.WriteLine(math.Groups[3].Value); } MatchCollection matchs = Regex.Matches(sre, @"是(\w+),"); for (int i = 0; i < matchs.Count; i++) { math=matchs[i]; if (math.Success) { Console.WriteLine(math.Groups[1].Value); //Console.WriteLine(math.Value); } } //获取html 中的超链接 string filestr = File.ReadAllText(@"c:/1.html"); filestr = filestr.Replace("\r", " ").Replace("\n"," "); matchs = Regex.Matches(filestr,"<a(.+?)herf=\"(.+?)\"(.*?)>(.+?)</a>",RegexOptions.IgnoreCase|RegexOptions.Multiline); for (int i = 0; i < matchs.Count; i++) { math = matchs[i]; if (math.Success) { string href = math.Groups[1].Value; string innerhtml = math.Groups[2].Value; Console.WriteLine("href={0},innerhtml={1}",href,innerhtml); } } Console.ReadLine(); } } }