[英]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.