下面我简要介绍一下C#中正则表达式的常用形式
常用的方法有:
Regex.IsMatch(value,pattern) 返回true 或者false
Match match = Regex.Match(input, pattern);
Regex.Replace(input,pattern,replacement)
Regex.Split(input,pattern)
具体使用详情还是看代码:
static void Main(string[] args) { //RegexIsMatch(); //RegexMatch(); //RegexReplace(); //RegexSplit(); Matches(); Console.ReadLine(); } /// <summary> /// 最基本的方法判断是否匹配 /// </summary> static void RegexIsMatch() { string[] values = { "111-22-3333", "111-2-3333" }; string pattern = @"^d{3}-d{2}-d{4}$"; foreach(var value in values) { if(Regex.IsMatch(value,pattern)) { Console.WriteLine("{0} is valid",value); } else { Console.WriteLine("{0} is not valid", value); } } } /// <summary> /// match方法返回Match类型 /// </summary> static void RegexMatch() { string input = "This is TianYun TianYun"; string pattern = @"(w+)s(1)"; Match match = Regex.Match(input, pattern); while (match.Success) { Console.WriteLine("Duplication {0} found",match.Groups[0].Value); match = match.NextMatch(); } } /// <summary> /// Replace method $& is the matched string,and the $$ is $ /// </summary> static void RegexReplace() { string input = "Total cost:103.44"; string pattern = @"d+.d{2}"; string replacement = "$$$&"; Console.WriteLine(Regex.Replace(input,pattern,replacement)); } /// <summary> /// split string by pattern, return array /// </summary> static void RegexSplit() { string input = "1. egg 2. bread 3. milk 4. coffee"; string pattern = @"d.s"; foreach (var s in Regex.Split(input,pattern)) { if (!string.IsNullOrEmpty(s)) { Console.WriteLine(s); } } } /// <summary> /// return Matches /// </summary> static void Matches() { MatchCollection matchs = Regex.Matches("abc123abc42abc54", @"abc"); foreach (Match match in matchs) { Console.WriteLine("{0} is found at {1}",match.Value,match.Index); Console.WriteLine("{0}",match.Result("$& hello This is match.Result")); } }