C#正則表達(dá)式之組與非捕獲組淺析
作者:chenglidexiaoxue
C#正則表達(dá)式之組與非捕獲組是什么呢?C#正則表達(dá)式之組與非捕獲組是如何使用的呢?C#正則表達(dá)式之組與非捕獲組代表什么意思呢?那么本文就向你介紹具體的內(nèi)容。
C#正則表達(dá)式之組與非捕獲組是什么呢?具體的使用是如何的呢?讓我們來(lái)看看具體的實(shí)例操作:
以下提供一些簡(jiǎn)單的C#正則表達(dá)式之組與非捕獲組示例:
- 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
- //正則表達(dá)式引擎會(huì)記憶“()”中匹配到的內(nèi)容,作為一個(gè)“組”,
- //并且可以通過(guò)索引的方式進(jìn)行引用。表達(dá)式中的“\1”,
- //用于反向引用表達(dá)式中出現(xiàn)的第一個(gè)組,即粗體標(biāo)識(shí)的第一個(gè)括號(hào)內(nèi)容,“\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
- }
- //獲取組中的內(nèi)容。注意,此處是Groups[1],
- //因?yàn)镚roups[0]是整個(gè)匹配的字符串,即整個(gè)變量x的內(nèi)容。
- 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
- }
- //可根據(jù)組名進(jìn)行索引。使用以下格式為標(biāo)識(shí)一個(gè)組的名稱(?﹤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
- }
- //刪除原字符串中重復(fù)出現(xiàn)的“nothing”。在表達(dá)式之外,
- //使用“$1”來(lái)引用第一個(gè)組,下面則是通過(guò)組名來(lái)引用:
- 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);//輸出:(空)
- }
- //在組前加上“?:”表示這是個(gè)“非捕獲組”,即引擎將不保存該組的內(nèi)容。
C#正則表達(dá)式之組與非捕獲組使用的基本內(nèi)容就向你介紹到這里,希望對(duì)你了解和學(xué)習(xí)C#正則表達(dá)式有所幫助。
【編輯推薦】
責(zé)任編輯:仲衡
來(lái)源:
CSDN博客