对 C# 和 JavaScript 的 正则 的疑问:
看了 MSDN 中对 C# 正则的一些例子,对这个例子的结果感到费解:
using System;
using System.Text.RegularExpressions;
public class RegexTest
{
public static void RunTest()
{
int counter;
Match m;
CaptureCollection cc;
GroupCollection gc;
// Look for groupings of "Abc".
Regex r = new Regex(@"(Abc)(\d+)");
// Define the string to search.
m = r.Match("XYZAbc2Abc2323Abc2323XYZAbcAb");
gc = m.Groups;
Console.WriteLine();
// Print the number of groups.
Console.WriteLine("所有匹配为" + gc.Count.ToString() + " 组");
Console.WriteLine();
// Loop through each group.
for (int i=0; i < gc.Count; i++)
{
cc = gc[i].Captures;
counter = cc.Count;
// Print number of captures in this group.
Console.WriteLine("第 " + i.ToString() + " 组的子匹配为 " + counter.ToString()+ " 组");
Console.WriteLine();
// Loop through each capture in group.
for (int ii = 0; ii < counter; ii++)
{
// Print capture and position.
Console.WriteLine(cc[ii] + " 开始位置 " +
cc[ii].Index);
Console.WriteLine();
}
}
}
public static void Main() {
RunTest();
}
}
和 JS 中同样的结果相差很大:
<script>
var xx= "XYZAbc2Abc2323Abc2323XYZAbcAb";
var p = /(Abc)(\d+)/g;
i=1;
while(a=p.exec(xx)){
document.write("第"+i+"个所有的匹配:"+a[0]+"。<BR>")
document.write(" 第1个子匹配:"+a[1]+"<BR>");
document.write(" 第2个子匹配:"+a[2]+"<BR>");
i++;
}
</script>
所以对 C# 的 GroupCollection 、() 的用法有点不解了。。。
要实现和 JS 一样的结果,C# 里该怎么做??