简体   繁体   English

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

[英]C#.NET regex not working as expected

Maybe It's because I'm totally fried right now, but this code: 也许这是因为我现在完全被炸了,但这段代码:

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());
            }
        }
    }

ought to produce the output: 应该产生输出:

2
vdi1.0.exe
1.0

if I'm not crazy. 如果我不疯了 Instead, it's just producing: 相反,它只是产生:

1
vdi1.0.exe

What am I missing? 我错过了什么?

Your Regular Expression will only return one Match object with 2 subgroups. 您的正则表达式只返回一个具有2个子组的Match对象。 You can access those groups using the Groups collection of the Match object. 您可以使用Match对象的Groups集合访问这些组。

Try something like: 尝试类似的东西:

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);
   }
}

This allows you to match multiple filenames in a single string, then loop through those matches, and grab each individual group from within the parent match. 这允许您在单个字符串中匹配多个文件名 ,然后遍历这些匹配,并从父匹配中获取每个单独的组。 This makes a bit more sense than returning a single, flattened out array like some languages. 这比像某些语言返回单个扁平化数组更有意义。 Also, I'd consider giving your groups names: 另外,我会考虑给你的团体名字:

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

Then, you can refer to groups by name: 然后,您可以按名称引用组:

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

This makes the code a bit more readable, and allows group offsets to change without breaking things. 这使代码更具可读性,并允许组偏移在不破坏的情况下进行更改。

Also, if you're always parsing only a single filename, there's no reason to loop through a MatchCollection at all. 此外,如果您始终只解析单个文件名,则根本没有理由循环使用MatchCollection You can change: 你可以改变:

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

To: 至:

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

To obtain a single Match object, and access each Group by name or index. 获取单个Match对象,并按名称或索引访问每个Group

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM