C#.NET正则表达式未按预期工作
也许是因为我现在完全疯了,但下面的代码:C#.NET正则表达式未按预期工作,c#,.net,regex,C#,.net,Regex,也许是因为我现在完全疯了,但下面的代码: static void Main(string[] args) { Regex regx = new Regex(@"^.*(vdi([0-9]+\.[0-9]+)\.exe).*$"); MatchCollection results = regx.Matches("vdi1.0.exe"); Console.WriteLine(results.Count); if (resul
static void Main(string[] args)
{
Regex regx = new Regex(@"^.*(vdi([0-9]+\.[0-9]+)\.exe).*$");
MatchCollection results = regx.Matches("vdi1.0.exe");
Console.WriteLine(results.Count);
if (results.Count > 0)
{
foreach (Match r in results)
{
Console.WriteLine(r.ToString());
}
}
}
应当产生产出:
2
vdi1.0.exe
1.0
如果我没疯的话。相反,它只是生产:
1
vdi1.0.exe
我缺少什么?您的正则表达式将只返回一个带有2个子组的
匹配对象。您可以使用Match
对象的groups
集合访问这些组
尝试以下方法:
foreach (Match r in results) // In your case, there will only be 1 match here
{
foreach(Group group in r.Groups) // Loop through the groups within your match
{
Console.WriteLine(group.Value);
}
}
这允许您在单个字符串中匹配多个文件名,然后循环这些匹配,并从父匹配中获取每个单独的组。这比像某些语言一样返回单个扁平数组更有意义。另外,我会考虑给你的组名称:< /P>
Regex regx = new Regex(@"^.*(?<filename>vdi(?<version>[0-9]+\.[0-9]+)\.exe).*$");
这使代码更具可读性,并允许组偏移量在不破坏内容的情况下进行更改
另外,如果您总是只解析一个文件名,那么根本没有理由在MatchCollection
中循环。您可以更改:
MatchCollection results = regx.Matches("vdi1.0.exe");
致:
要获得单个匹配
对象,并按名称或索引访问每个组
。我认为您必须使用组
属性访问子组。Mike是正确的。你把匹配和组混淆了。顺便说一句,Regex如何将组1.1
?这不会在vdi1.0.exe
中发生。你是说1.0
?@voithos是的,我说了。哎呀。@MikeChristensen没错-我忘了。我是唯一一个完全没有这种直觉的人吗?谢谢迈克-我甚至不知道如何命名群组。我现在就是这样做的。
MatchCollection results = regx.Matches("vdi1.0.exe");
Match result = regx.Match("vdi1.0.exe");