C#.NET正则表达式未按预期工作

本文关键字:工作 NET 正则表达式 | 更新日期: 2023-09-27 18:23:42

也许是因为我现在完全被炸了,但这段代码:

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

我错过了什么?

C#.NET正则表达式未按预期工作

正则表达式将只返回一个具有2个子组的Match对象。您可以使用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);
   }
}

这允许您在单个字符串中匹配多个文件名,然后循环通过这些匹配,并从父匹配中获取每个单独的组。这比像某些语言那样返回一个扁平的数组更有意义。此外,我会考虑给你的小组命名:

Regex regx = new Regex(@"^.*(?<filename>vdi(?<version>[0-9]+'.[0-9]+)'.exe).*$");

然后,您可以通过名称来指代组:

string file = r.Groups["filename"].Value;
string ver = r.Groups["version"].Value;

这使得代码更加可读,并允许组偏移量在不破坏内容的情况下进行更改。

此外,如果您总是只解析一个文件名,那么根本没有理由循环使用MatchCollection。您可以更改:

MatchCollection results = regx.Matches("vdi1.0.exe");

收件人:

Match result = regx.Match("vdi1.0.exe");

获取单个Match对象,并按名称或索引访问每个Group