using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text.RegularExpressions; namespace codeTest { class Program { static void Main(string[] args) { string[] strArray = { "1111-222-333", "1111-2222-3333" }; string pattern = @"^\d{4}-\d{3}-\d{3}$"; foreach (var item in strArray) { if (Regex.IsMatch(item, pattern)) { Console.WriteLine("{0} is vaild", item); } else { Console.WriteLine("{0} is not vaild", item); } } RegexIsMacth(); RegexReplace(); RegexSplit(); RegexMacths(); RegexGroup(); Console.ReadLine(); } static void RegexIsMacth() { string input = " this is my name my name"; string pattern = @"\s\w{4}\s"; Match match = Regex.Match(input,pattern); while(match.Success) { Console.WriteLine(match.Groups[0].Value); match = match.NextMatch(); } } static void RegexReplace() { string input = " this is my name my name"; string pattern = @"\s\w{4}\s"; string replacement = " 匹配 "; Console.WriteLine(input); Console.WriteLine(Regex.Replace(input, pattern, replacement)); } static void RegexSplit() { string input = "1.A 2.B 3.C 4.D "; string pattern = @"\s"; foreach (var item in Regex.Split(input,pattern)) { if (!string.IsNullOrEmpty(item)) { Console.WriteLine(item); } } } static void RegexMacths() { Regex regex = new Regex(@"\d+"); MatchCollection matchs; matchs = regex.Matches("123abc333adsa123123asdasd123123"); foreach (Match item in matchs) { Console.WriteLine("value is {0},index is {1}", item.Value,item.Index); Console.WriteLine("Result is {0}",item.Result("[$&]")); } } static void RegexGroup() { string input = "born: July 28, 1989"; string pattern = @"\b(\w+)\s(\d{1,2}),\s(\d{4})\b"; Match match = Regex.Match(input, pattern); for (int i = 0; i < match.Groups.Count; i++) { Console.WriteLine("Group value is {0},index is {1}",match.Groups[i].Value,match.Groups[i].Index); } } } }
推荐使用微软的Regular Expression Tester工具测试
时间: 2024-11-05 11:31:06