[英]How do I access the .Name of a regex Group?
I have a regex that is like this:我有一个像这样的正则表达式:
var a = new Regex("(?<PageNumber>.{2})(?<ListType>.{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
Match:比赛:
a.Match("02KLThisIsATest");
When I then after a successfull match use:当我在成功匹配后使用时:
foreach (Group gr in match.Groups)
{
...
}
I can see clearly in the debugger that the "Name" is filled out and thus "0", "Page'Number", "ListType".我可以在调试器中清楚地看到“名称”已填写,因此“0”、“Page'Number”、“ListType”。 BUT I cannot in the source use: gr.Name.
但我不能在源代码中使用:gr.Name。 The compiler just says "no there is no Name".
编译器只是说“不,没有名字”。
Now my question is: How can I access the Name?现在我的问题是:如何访问名称?
try this尝试这个
var a = new Regex("(?<PageNumber>.{2})(?<ListType>.{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
GroupCollection groups = a.Match("02KLThisIsATest").Groups;
var names = a.GetGroupNames();
foreach (var grpName in names )
{
Console.WriteLine("Group: {0}, Value: {1}", grpName, groups[grpName].Value);
}
It works as expected when I am running on .Net runtime > 4.6.2.当我在 .Net 运行时 > 4.6.2 上运行时,它按预期工作。 Some properties are not accessible because of boxing\\ unboxing of an object to an underlying abstract or base type so that extra members in inherited or child class are hidden.
由于将对象装箱\\拆箱为基础抽象或基类型,因此某些属性无法访问,从而隐藏继承或子类中的额外成员。 I made it to
dynamic
to expose all public\\ protected members.我将其设为
dynamic
以公开所有公共\\受保护成员。
Related: Why some properties/fields are being visible in debugger, but not accessible from the code?相关: 为什么某些属性/字段在调试器中可见,但无法从代码访问?
public static void Main(string[] args)
{
var a = new Regex("(?<PageNumber>.{2})(?<ListType>.{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
var match = a.Match("02KLThisIsATest");
foreach (dynamic gr in match.Groups)
{
//Your code goes here
Console.WriteLine(gr.Name + " | " + gr.Value);
}
}
Published the example in, https://rextester.com/FKYG47557在https://rextester.com/FKYG47557 中发布了示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.