根據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