[英]Regex for multiple filename string patterns
I want to parse certain information from given patterns, which are as follows:我想从给定的模式中解析某些信息,如下所示:
/root/test/subfolder/
relative/folder/
index.html
/root/test/style.css
test/test2/test3/testN/
I created a regex but it doesn't match multiple strings like root/, test/ only the last instance.我创建了一个正则表达式,但它不匹配多个字符串,如 root/,test/ 仅匹配最后一个实例。 My code:我的代码:
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();
I want to have first slash as optional, then path with / at the end and optional filename at the end.我想将第一个斜杠作为可选,然后在末尾带有 / 的路径和最后的可选文件名。
Repeated capturing groups always capture only the last repetition.重复捕获组总是只捕获最后一次重复。 But you can capture the entire repeated group instead (and use non-capturing parentheses (?:...)
for the repeated group:但是您可以改为捕获整个重复组(并对重复组使用非捕获括号(?:...)
:
Regex re = new Regex(@"^(/?)((?:[\w\.]+/)*)([\w\.]+)?$
This will work in other regex flavors, too.这也适用于其他正则表达式风格。 .NET offers another feature, though: It is possible to access the individual matches of a repeated capturing group .不过,.NET 提供了另一个功能:可以访问重复捕获组的单个匹配项。 Using your regex:使用您的正则表达式:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.