我想从给定的模式中解析某些信息,如下所示:
/root/test/subfolder/
relative/folder/
index.html
/root/test/style.css
test/test2/test3/testN/
我创建了一个正则表达式,但它不匹配多个字符串,如root /,test / only最后一个实例。我的代码:
Regex re = new Regex(@"^(/?)([\w\.]+/)*([\w\.]+)?$");
foreach (Group gr in re.Match("/templates/base/test/header.html").Groups)
Console.WriteLine(gr + " @ " + gr.Index.ToString());
Console.ReadKey();
我希望第一个斜杠是可选的,然后是/在末尾的路径和最后的可选文件名。
答案 0 :(得分:1)
重复捕获组始终只捕获最后一次重复。但您可以捕获整个重复的组(并使用非捕获括号(?:...)
作为重复的组:
Regex re = new Regex(@"^(/?)((?:[\w\.]+/)*)([\w\.]+)?$
这也适用于其他正则表达式。 .NET提供了另一个功能:可以access the individual matches of a repeated capturing group。使用你的正则表达式:
Match match = Regex.Match(input, @"^(/?)([\w\.]+/)*([\w\.]+)?$");
foreach (Capture capture in match.Groups[2].Captures) {
Console.WriteLine(" Capture {0}: {1}", captureCtr, capture.Value);
captureCtr += 1;
}