[英]C#.NET regex not working as expected
也许这是因为我现在完全被炸了,但这段代码:
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
对象。 您可以使用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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.