C#正则表达式整理备忘 4

来源:互联网 发布:微信淘宝客源码 编辑:程序博客网 时间:2024/06/05 00:49

(7)组与非捕获组
以下提供一些简单的示例:

Code
string x = "Live for nothing,die for something";
string y = "Live for nothing,die for somebody";
Regex r
= new Regex(@"^Live ([a-z]{3}) no([a-z]{5}),die /1 some/2$");
Console.WriteLine(
"x match count:" + r.Matches(x).Count);//1
Console.WriteLine("y match count:" + r.Matches(y).Count);//0
//正则表达式引擎会记忆“()”中匹配到的内容,作为一个“组”,并且可以通过索引的方式进行引用。表达式中的“/1”,用于反向引用表达式中出现的第一个组,即粗体标识的第一个括号内容,“/2”则依此类推。

string x = "Live for nothing,die for something";
Regex r
= new Regex(@"^Live for no([a-z]{5}),die for some/1$");
if (r.IsMatch(x))
{
     Console.WriteLine(
"group1 value:" + r.Match(x).Groups[1].Value);//输出:thing
}

//获取组中的内容。注意,此处是Groups[1],因为Groups[0]是整个匹配的字符串,即整个变量x的内容。

string x = "Live for nothing,die for something";
Regex r
= new Regex(@"^Live for no(?<g1>[a-z]{5}),die for some/1$");
if (r.IsMatch(x))
{
     Console.WriteLine(
"group1 value:" + r.Match(x).Groups["g1"].Value);//输出:thing
}

//可根据组名进行索引。使用以下格式为标识一个组的名称(?<groupname>…)。

string x = "Live for nothing nothing";
Regex r
= new Regex(@"([a-z]+) /1");
if (r.IsMatch(x))
{
     x
= r.Replace(x, "$1");
     Console.WriteLine(
"var x:" + x);//输出:Live for nothing
}

//删除原字符串中重复出现的“nothing”。在表达式之外,使用“$1”来引用第一个组,下面则是通过组名来引用:
string x = "Live for nothing nothing";
Regex r
= new Regex(@"(?<g1>[a-z]+) /1");
if (r.IsMatch(x))
{
     x
= r.Replace(x, "${g1}");
     Console.WriteLine(
"var x:" + x);//输出:Live for nothing
}


string x = "Live for nothing";
Regex r
= new Regex(@"^Live for no(?:[a-z]{5})$");
if (r.IsMatch(x))
{
     Console.WriteLine(
"group1 value:" + r.Match(x).Groups[1].Value);//输出:(空)
}

//在组前加上“?:”表示这是个“非捕获组”,即引擎将不保存该组的内容。

 

Code
string x = "Live for nothing,die for something";
Regex r1
= new Regex(@".*thing");
if (r1.IsMatch(x))
{
     Console.WriteLine(
"match:" + r1.Match(x).Value);//输出:Live for nothing,die for something
}

Regex r2
= new Regex(@".*?thing");
if (r2.IsMatch(x))
{
     Console.WriteLine(
"match:" + r2.Match(x).Value);//输出:Live for nothing
}

原创粉丝点击