string x = "Live for nothing,die for something";
Regex r = new Regex(@".*thing");
if (r.IsMatch(x))
{
Console.WriteLine("match:" + r.Match(x).Value);//输出:Live for nothing,die for something
}
Regex r = new Regex(@".*?thing");
if (r.IsMatch(x))
{
Console.WriteLine("match:" + r.Match(x).Value);//输出:Live for nothing
}
(9)回溯与非回溯
使用“(?>…)”方式进行非回溯声明。由于正则表达式引擎的贪婪特性,导致它在某些情况下,将进行回溯以获得匹配,请看下面的示例:
string x = "Live for nothing,die for something";
Regex r = new Regex(@".*thing,");
if (r.IsMatch(x))
{
Console.WriteLine("match:" + r.Match(x).Value);//输出:Live for nothing,
}
Regex r = new Regex(@"(?>.*)thing,");
if (r.IsMatch(x))//不匹配
{
Console.WriteLine("match:" + r.Match(x).Value);
}
//在r中,“.*”由于其贪婪特性,将一直匹配到字符串的最后,随后匹配“thing”,但在匹配“,”时失败,此时引擎将回溯,并在“thing,”处匹配成功
//在r中,由于强制非回溯,所以整个表达式匹配失败。
(10)正向预搜索、反向预搜索
正向预搜索声明格式:正声明 “(?=…)”,负声明 “(?!...)” ,声明本身不作为最终匹配结果的一部分,请看下面的示例:
string x = " used free";
Regex r = new Regex(@"/d{}(?= used)");
if (r.Matches(x).Count==)
{
Console.WriteLine("r match:" + r.Match(x).Value);//输出:
}
Regex r = new Regex(@"/d{}(?! used)");
if (r.Matches(x).Count==)
{
Console.WriteLine("r match:" + r.Match(x).Value); //输出:
}
//r中的正声明表示必须保证在四位数字的后面必须紧跟着“ used”,r2中的负声明表示四位数字之后不能跟有“ used”
反向预搜索声明格式:正声明“(?<=)”,负声明“(?<!)”,声明本身不作为最终匹配结果的一部分,请看下面的示例:
string x = "used: free:";
Regex r = new Regex(@"(?<=used:)/d{}");
if (r.Matches(x).Count==)
{
Console.WriteLine("r match:" + r.Match(x).Value);//输出:
}
Regex r = new Regex(@"(?<!used:)/d{}");
if (r.Matches(x).Count==)
{
Console.WriteLine("r match:" + r.Match(x).Value);//输出:
}
//r中的反向正声明表示在4位数字之前必须紧跟着“used:”,r2中的反向负声明表示在4位数字之前必须紧跟着除“used:”之外的字符串










