对 C# 和 JavaScript 的 正则 的疑问:

bflovesnow 2004-12-29 05:33:44
看了 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# 里该怎么做??
...全文
81 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
孟子E章 2004-12-29
  • 打赏
  • 举报
回复
http://blog.joycode.com/ghj/archive/2004/08/17/30835.aspx
nga96 2004-12-29
  • 打赏
  • 举报
回复
我也不理解,兄弟,不知为什么的
mathsword 2004-12-29
  • 打赏
  • 举报
回复
我只是该了你的runtest函数,你直接拷到vs里边运行。
看看你对 Capture和group的理解是不是正确的?
mathsword 2004-12-29
  • 打赏
  • 举报
回复
是你的理解错误,我花了一点时间给你弄出来了。
public void RunTest()
{
Match m;
GroupCollection gc;

string regex = "(Abc)(\\d+)";
System.Text.RegularExpressions.RegexOptions options = ((System.Text.RegularExpressions.RegexOptions.IgnorePatternWhitespace | System.Text.RegularExpressions.RegexOptions.Multiline)
| System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex, options);

m = reg.Match("XYZAbc2Abc2323Abc2323XYZAbcAb");
gc = m.Groups;
while (m.Success)
{
Console.WriteLine("Match=[" + m + "]"+"\n");
// Display Group1 and its capture set.
Group g1 = m.Groups[1];
foreach (Capture c1 in g1.Captures)
{
Console.WriteLine("Capture1=[" + c1 + "]"+"\n");
}
// Display Group2 and its capture set.
Group g2 = m.Groups[2];
foreach (Capture c2 in g2.Captures)
{
Console.WriteLine("Capture2=[" + c2 + "]"+"\n");
}
// Advance to the next match.
m = m.NextMatch();
}
}

110,535

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧