根据Regex
文档,使用RegexOptions.ExplicitCapture
使得正则表达式只匹配命名组,如(?<groupName>...)
;但在行动上它做了一些有点不同的事情。如何使正则表达式只捕获命名组
考虑的几行代码:
static void Main(string[] args) {
Regex r = new Regex(
@"(?<code>^(?<l1>[\d]{2})/(?<l2>[\d]{3})/(?<l3>[\d]{2})$|^(?<l1>[\d]{2})/(?<l2>[\d]{3})$|(?<l1>^[\d]{2}$))"
, RegexOptions.ExplicitCapture
);
var x = r.Match("32/123/03");
r.GetGroupNames().ToList().ForEach(gn => {
Console.WriteLine("GroupName:{0,5} --> Value: {1}", gn, x.Groups[gn].Success ? x.Groups[gn].Value : "");
});
}
当你运行这段代码,你会看到的结果中包含一个名为组,而我没有在我的正则表达式命名0组!
GroupName: 0 --> Value: 32/123/03
GroupName: code --> Value: 32/123/03
GroupName: l1 --> Value: 32
GroupName: l2 --> Value: 123
GroupName: l3 --> Value: 03
Press any key to continue . . .
请问有人请向我解释这种行为?
的*零组*匹配整个正则表达式 – 2015-04-01 18:56:43
@AlexK。你的意思是我不得不忽视第一组? – Achilles 2015-04-01 19:07:38