实例详解C#正则表达式

2019-12-30 11:32:37丽君

$  表示其前面的字符必须位于字符串的结束处
/b  匹配一个单词的边界
/B  匹配一个非单词的边界

另外,还包括:/A  前面的字符必须位于字符处的开始处,/z  前面的字符必须位于字符串的结束处,/Z  前面的字符必须位于字符串的结束处,或者位于换行符前

下面提供一些简单的示例:


string i = "Live for nothing,die for something";
 Regex r = new Regex("^Live for nothing,die for something$");
 //r.IsMatch(i) true
 Regex r = new Regex("^Live for nothing,die for some$");
 //r.IsMatch(i) false
 Regex r = new Regex("^Live for nothing,die for some");
 //r.IsMatch(i) true
 string i = @"Live for nothing,
 die for something";//多行
 Regex r = new Regex("^Live for nothing,die for something$");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,die for something$", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,/r/ndie for something$");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,$");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,$", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,/r/n$");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,/r/n$", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,/r$");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,/r$", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^die for something$");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^die for something$", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("$");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("$", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex("^Live for nothing,/r$/n^die for something$", RegexOptions.Multiline);
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 //对于一个多行字符串,在设置了Multiline选项之后,^和$将出现多次匹配。
 string i = "Live for nothing,die for something";
 string m = "Live for nothing,die for some thing";
 Regex r = new Regex(@"/bthing/b");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex(@"thing/b");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 Regex r = new Regex(@"/bthing/b");
 Console.WriteLine("r match count:" + r.Matches(m).Count);//
 Regex r = new Regex(@"/bfor something/b");
 Console.WriteLine("r match count:" + r.Matches(i).Count);//
 ///b通常用于约束一个完整的单词