同正则表达式捕获组的能实现不同个数吗? string x = "abaaabb";
Regex r1 = new Regex(@"(?<a>a)|(?<b>b)");
foreach (Match m in r1.Matches(x))
{
Console.WriteLine("a = {0}",m.Groups["a"].Value);
}
foreach (Match m in r1.Matches(x))
{
Console.WriteLine("b = {0}", m.Groups["b"].Value);
}
Console.ReadLine();上面的代码,是相同个数,竟然出现了很多个空值来补成相同个数,不知道为什么????
Regex r1 = new Regex(@"(?<a>a)|(?<b>b)");
foreach (Match m in r1.Matches(x))
{
Console.WriteLine("a = {0}",m.Groups["a"].Value);
}
foreach (Match m in r1.Matches(x))
{
Console.WriteLine("b = {0}", m.Groups["b"].Value);
}
Console.ReadLine();上面的代码,是相同个数,竟然出现了很多个空值来补成相同个数,不知道为什么????
解决方案 »
- 请问在foreach里怎么用List
- 前台javascript改变dropdownlist控件的选中项时,为何不能引发该控件的change事件自动回发呢?
- 奇怪~!!C#无法Select出Access中的数据
- "求解"画图问题
- 如何改变DATAGRIDVIEW中BUTTON列的某个CELL的颜色
- 在一个函数体中能否用 ref 呢?
- 写事件日志的问题!
- 在线等,马上结贴:局域网用winform 上传下载文件的例子,不用webservice 快点来
- 西门子的2128手机支持AT指令吗?能做gsm/gprs模块来开发吗?
- 怎么判断一个元素在不在一个集合里面?
- 求助在窗体的textBox中相互拖拽数据
- 图片打包上传。
你这样写结果捕获的个数肯定相同啊,因为字符串不是a就是b,也就是都是满足上面的正则的
结果捕获的个数就是字符串的长度了
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{ string test = "1234abcdefg";
Regex reg = new Regex(@"(?<num>[0-9])+(?<ch>[a-z])+");
Match m = reg.Match(test);
StringBuilder sb;
if (m.Success)
{ Console.WriteLine("result:" + m.Value + "\n"); Console.WriteLine("Group:" + m.Groups["num"].Value + "\n--------------\n"); foreach (Capture c in m.Groups["num"].Captures)
{ Console.WriteLine("Capture:" + c + "\n"); }
Console.WriteLine("Group:" + m.Groups["ch"].Value + "\n--------------\n"); foreach (Capture c in m.Groups["ch"].Captures)
{ Console.WriteLine("Capture:" + c + "\n"); } }
} }
}
没有实际需求,这种探讨我认为是没什么意义的这是跟语言相关的,在其它语言中,比如记得TCL中引用未参与匹配的捕获组,是会抛异常的
而在,.NET中,没有匹配到,或是没有参与匹配的捕获组,如果去引用它的话,会直接返回一个空字符串
甚至于你去引用一个根本就不存在的捕获组,也是一样的
string x = "abaaabb";
Regex r1 = new Regex(@"(?<a>a)|(?<b>b)");
foreach (Match m in r1.Matches(x))
{
richTextBox2.Text += string.Format("c = {0}", m.Groups["c"].Value) + "\n";
}