正则表达式的匹配问题

aloneone 2013-11-13 11:33:16
代码是帮助的示例,仅改动了text与pat的值。
        private void button4_Click(object sender, EventArgs e)
{
string text = "select * from blue order by a";
string pat = @"(select)|(from)|(order)|(by)";
// Compile the regular expression.
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
// Match the regular expression pattern against a text string.
Match m = r.Match(text);
int matchCount = 0;
while (m.Success)
{
Console.WriteLine("Match" + (++matchCount));
for (int i = 1; i <= 2; i++)
{
Group g = m.Groups[i];
Console.WriteLine("Group" + i + "='" + g + "'");
CaptureCollection cc = g.Captures;
for (int j = 0; j < cc.Count; j++)
{
Capture c = cc[j];
System.Console.WriteLine("Capture" + j + "='" + c + "', Position=" + c.Index);
}
}
m = m.NextMatch();
}
}

====我想捕获select/from/order/by这四个关键字,输出结果如下:
Match1
Group1='select'
Capture0='select', Position=0
Group2=''
Match2
Group1=''
Group2='from'
Capture0='from', Position=9
Match3
Group1=''
Group2=''
Match4
Group1=''
Group2=''
====我的问题有两个(1个问题20分)
1.为什么会有Group1或Group2为空字符('')的捕获结果?
2.为什么order与by未被捕获到?
...全文
216 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
q107770540 2013-11-14
  • 打赏
  • 举报
回复
这代码写的够乱的,挺简单一事让你搞复杂了:
		 string text = "select * from blue order by a";
			string pat = @"(?:select)|(?:from)|(?:order)|(?:by)";
			// Compile the regular expression.
			Regex r = new Regex(pat, RegexOptions.IgnoreCase);
			
			foreach(Match m in r.Matches(text))		
			{
			  foreach(Capture c in m.Captures)
			  	Console.WriteLine(c.Value);
			}
游戏人间 2013-11-14
  • 打赏
  • 举报
回复
for (int i = 1; i <= 2; i++) 为什么是<=2呢? 那不是只能显示2组吗? 加 上order by 不是有4组.

110,534

社区成员

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

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

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