2011-04-23 41 views
18

這是我的源字符串:通過正則表達式循環比賽

<box><3> 
<table><1> 
<chair><8> 

這是我的正則表達式百通:

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

這是我的項目類

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

這是我的項目集合;

List<Item> OrderList = new List(Item); 

我想使用基於源字符串的Item來填充該列表。 這是我的功能。它不工作。

Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\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

我得到它的工作。 Thans尋求幫助。

+2

剛剛運行它 - 像預期一樣工作(列表中的3個項目)。 – ChrisWue 2011-04-23 23:39:42

+0

我發現我的錯誤。 – Hooch 2011-04-24 00:23:35

+2

你能分享嗎?如果他遇到同樣的問題,可能會幫助別人。 – ChrisWue 2011-04-24 01:24:33

回答

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

     Console.ReadLine(); 
    } 
} 

返回3匹配我。你的問題必須在其他地方。

8

供將來參考我想要記錄上述代碼轉換爲使用聲明性的方法作爲LinqPad代碼片斷:

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

隨着輸出:

List of matches

+0

上找到該截圖中的程序?它是你自己的程序嗎? – Hooch 2011-12-14 20:16:40

+1

這是由LinqPad的Dump()擴展方法生成的。您可以將Dump()貼在大多數對象的末尾,並將輸出對象的格式化表示。 LinqPad只是用於編寫/評估C#代碼http://www.linqpad.net/的特別工具。上面的代碼可以被複制並直接粘貼到LinqPad中,並且會生成表格。 – 2011-12-14 22:29:28

+1

然後,我都喜歡,lawl ...我要點擊「編輯」看到製作這樣一個漂亮的表的降價。 – Suamere 2017-09-05 13:32:12

5

爲了解決剛剛標題(「循環正則表達式匹配」),您可以:

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

這會將所有捕獲的值「扁平化」到一個列表中。要維護捕獲組,請使用Select而不是SelectMany來獲取列表的列表。