通过正则表达式匹配循环

这是我的源字符串:

 

这是我的Regex Patern:

 <(?\w+?)><(?\d+?)> 

这是我的Item类

 class Item { string Name; int count; //(...) } 

这是我的物品collections;

 List OrderList = new List(Item); 

我想根据源字符串使用Item填充该列表。 这是我的function。 它不起作用。

 Regex ItemRegex = new Regex(@"<(?\w+?)><(?\d+?)>", RegexOptions.Compiled); foreach (Match ItemMatch in ItemRegex.Matches(sourceString)) { Item temp = new Item(ItemMatch.Groups["item"].ToString(), int.Parse(ItemMatch.Groups["count"].ToString())); OrderList.Add(temp); } 

Threre可能是一些小错误,比如在这个例子中丢失字母,因为这是我在我的应用程序中更容易的版本。

问题是,最后我在OrderList中只有一个Item。

UPDATE

我搞定了。 寻求帮助。

 class Program { static void Main(string[] args) { string sourceString = @"<3> 
<1> <8>"; Regex ItemRegex = new Regex(@"<(?\w+?)><(?\d+?)>", RegexOptions.Compiled); foreach (Match ItemMatch in ItemRegex.Matches(sourceString)) { Console.WriteLine(ItemMatch); } Console.ReadLine(); } }

为我返回3场比赛。 你的问题必须在其他地方。

为了将来参考,我想记录上面转换为使用声明方法作为LinqPad代码片段的代码:

 var sourceString = @"<3> <1> <8>"; var count = 0; var ItemRegex = new Regex(@"<(?[^>]+)><(?[^>]*)>", RegexOptions.Compiled); var OrderList = ItemRegex.Matches(sourceString) .Cast() .Select(m => new { Name = m.Groups["item"].ToString(), Count = int.TryParse(m.Groups["count"].ToString(), out count) ? count : 0, }) .ToList(); OrderList.Dump();

带输出:

比赛清单

要解决问题的标题(“循环使用正则表达式匹配”),您可以:

 var lookfor = @"something (with) multiple (pattern) (groups)"; var found = Regex.Matches(source, lookfor, regexoptions); var captured = found // linq-ify into list .Cast() // flatten to single list .SelectMany(o => // linq-ify o.Groups.Cast() // don't need the pattern .Skip(1) // select what you wanted .Select(c => c.Value)); 

这会将所有捕获的值“展平”到单个列表。 要维护捕获组,请使用Select而不是SelectMany来获取列表列表。