public static void main() { string s = "aabbc11asd"; regex reg = new regex(@"(/w)/1"); matchcollection matches = reg.matches(s); foreach(match m in matches) console.writeline(m.value); console.readline(); }
返回結果為aa bb 11
輔助匹配組
以下幾種組結構,括號中的pattern都不作為匹配結果的一部分進行保存
1、正聲明(?=)
涵義:括號中的模式必須出現在聲明右側,但不作為匹配的一部分
public static void main() { string s = "c#.net,vb.net,php,java,jscript.net"; regex reg = new regex(@"[/w/#]+(?=/.net)",regexoptions.compiled); matchcollection mc = reg.matches(s); foreach(match m in mc) console.writeline(m.value); console.readline(); //輸出 c# vb jscript }
可以看到匹配引擎要求匹配.net,但卻不把.net放到匹配結果中
2、負聲明(?!)
涵義:括號中的模式必須不出現在聲明右側
下例演示如何取得一個<a>標簽對中的全部內容,即使其中包含別的html tag。
public static void main() { string newscontent = @"url:<a href=""1.html""><img src=""http://m.survivalescaperooms.com/htmldata/2006-03-23/http://m.survivalescaperooms.com/htmldata/2006-03-23/1.gif"">test<span color:red;"">regex</span></a>."; regex regend = new regex(@"</s*a[^>]*>([^<]|<(?!/a))*</s*/a/s*>",regexoptions.multiline);