我们想找出一个使用英文字母开头的用户名,编写代码如下:
复制代码
string pattern = @"^[A-Za-z]+.*";
Regex regex = new Regex(pattern);
if (regex.IsMatch(str))
Console.WriteLine(regex.Match(str).Value);
else
Console.WriteLine("Mismatch!");
//结果为:Mismatch!
错误分析:
(^)是字符串的起始锚定,str的第一个字符是一个中文字,所以匹配不上。我们就可以使用多行模式来改变(^)的含义,使它匹配每一行的起始,而不是整个字符串的起始。
更改代码如下:
复制代码
string pattern = @"^[A-Za-z]+.*";
Regex regex = new Regex(pattern, RegexOptions.Multiline);
if (regex.IsMatch(str))
Console.WriteLine(regex.Match(str).Value);
else
Console.WriteLine("Mismatch!");
//结果为:TerryLee
同时,多行模式也会改变($)的含义,使它匹配每一行的结尾,而不是整个字符串的结尾。
与(^)和($)不同的是,(A)和(Z)并不受多行模式的影响,永远匹配整个字符串的起始和结尾。
多行模式的嵌入修饰符:(?m)与(?-m)
3. 忽略大小写(IgnoreCase)










