RegEx:将相同的字符串匹配到2个命名组中

时间:2012-11-27 07:05:04

标签: c# .net regex

我有以下C#代码:

string MyString = "<a href=\"magnet:?xt=urn:btih:7f3befa467c4cac0787286c87ea264a0606066f5&dn=some.file.name.zip&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80\" title=\"Download this torrent using magnet\">...</a>[Some unwanted stuff here]<a href=[Another]>";

MatchCollection MyMatches = Regex.Matches(MyString, "(?<URL>magnet:\\?.*?)(?:\"|')");           
foreach(Match MyMatch in MyMatches)
{
    MessageBox.Show(MyMatch.Groups["URL"].Value);
}

我的问题是:如何将&dn=some.file.name.zip放入名为<File>的命名组?

1 个答案:

答案 0 :(得分:1)

string MyString = "<a href=\"magnet:?xt=urn:btih:7f3befa467c4cac0787286c87ea264a0606066f5&dn=some.file.name.zip&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80\" title=\"Download this torrent using magnet\">...</a>[Some unwanted stuff here]<a href=[Another]>";

MatchCollection MyMatches = Regex.Matches(MyString, "(?<URL>magnet:\\?.*(&dn=(?<File>[^&]+)).*?)(?:\"|')");           
foreach(Match MyMatch in MyMatches)
{
    MessageBox.Show(MyMatch.Groups["URL"].Value);
    MessageBox.Show(MyMatch.Groups["File"].Value);
}