项目结构
贪婪模式
string inputMsg = "111。11。1。";Match match = Regex.Match(inputMsg, ".+?。");// 111。MatchCollection collection = Regex.Matches(inputMsg, "(.+?)。");Match item1 = collection[0];// 111。Match item2 = collection[1];// 11。Match item3 = collection[2];// 1。
常用正则
string inputMsg = "绿色家园01栋02单元0304号";MatchCollection collection = Regex.Matches(inputMsg, @"(\D+)(\d+)(\D+)(\d+)(\D+)(\d+)(\D+)");string item1 = collection[0].Groups[1].Value;// 绿色家园string item2 = collection[0].Groups[2].Value;// 01string item3 = collection[0].Groups[3].Value;// 栋string item4 = collection[0].Groups[4].Value;// 02string item5 = collection[0].Groups[5].Value;// 单元string item6 = collection[0].Groups[6].Value;// 0304string item7 = collection[0].Groups[7].Value;// 号
反向引用
string inputMsg = "我我我我我爱爱爱爱你你你";inputMsg = Regex.Replace(inputMsg, @"(.)\1+", "$1");// 我爱你
基本元字符
Match match1 = Regex.Match("abc", ".+");Match match2 = Regex.Match("abc", "a[bB]c");Match match3 = Regex.Match("aBc", "a[^0-9a-z]c");Match match4 = Regex.Match("abc", "a(B|b)c");Match match5 = Regex.Match("abc", "abc*");Match match6 = Regex.Match("a123b", "a[0-9]{3}b");Match match7 = Regex.Match("a123b", "a[0-9]{3,4}b");Match match8 = Regex.Match("a123b", "a[0-9]{3,}b");Match match9 = Regex.Match("abc123", "^abc");Match match10 = Regex.Match("abc123", "123$");//等价于 [0-9]Match match11 = Regex.Match("a123b", @"a\d+b");//等价于 [0-9a-zA-Z] 在C# 中还包括中文字符Match match12 = Regex.Match("Aabc3B", @"A\w+B");//表示所有那些空白符,不可见字符,包括 换行,tab,空格Match match13 = Regex.Match("abc b c", @"abc\s+b\s+c");
IsMatch
bool b1 = Regex.IsMatch("a123c", "^a.+c$");
匹配转移字符
//\\\\dstring msg = Regex.Escape("\\d");
Replace
//我的生日是2010-05-21耶我的生日是2000-03-11耶string msg1 = "我的生日是05/21/2010耶我的生日是03/11/2000耶";msg1 = Regex.Replace(msg1, @"(\d{2})/(\d{2})/(\d{4})", "$3-$1-$2");//hello 【welcome】 to 【China】, hello 【welcome】 to 【China】string msg2 = "hello 'welcome' to 'China', hello 'welcome' to 'China'";msg2 = Regex.Replace(msg2, @"'(.+?)'", @"【$1】");