2013-04-05 179 views
0

我仍在學習正則表達式,我對它很陌生。正則表達式 - 從逗號分隔的圓括號內獲取數據

我有以下數據

add(2,3); 

我想從括號內獲得整數值「()」同時獲得由分隔的以下的整數「」的各個值將被存儲爲在一個數組列表的可變

在其預期的結果應該是

result[0] = 2; 
result[1] = 3; 

另一個採樣數據將是

add(2,3,1); 

,其結果將是以下

result[0] = 2; 
result[1] = 3; 
result[2] = 1; 

我已經用下面的表達式試圖「@‘\ d +’」但是當我解析它讀取所有的數字字符串中的數據。我嘗試過的另一個表達式是'((\ d \,\ d))',但它成功讀取第一個示例但不是第二個。

整個代碼片斷

string s = "add(2,3,1);"; 
    MatchCollection matches = Regex.Matches(s, @"\d+"); 

    string[] result = matches.Cast<Match>().Take(10).Select(match => match.Value).ToArray(); 

請請告知。謝謝。

+1

'\ d +'全'2,3,1'相匹配?這聽起來不對。 – 2013-04-05 07:32:20

+0

它匹配個別的數字結果。其中im不是真的很喜歡,因爲除了'()'中的字符串外,還有其他數字。 – user2248001 2013-04-05 07:39:48

回答

0

我會使用命名組,並通過一組不同的捕獲迭代,如下。我加在測試字符串一些虛擬號碼,以確保它們不會捕獲:

string s = "12 3 4 142 add(2 , 3,1); 21, 13 123 123,"; 
var matches = Regex.Matches(s, @"\(\s*(?<num>\d+)\s*(\,\s*(?<num>\d+)\s*)*\)"); 

foreach (Match match in matches) 
    foreach (Capture cpt in match.Groups["num"].Captures) 
     Console.WriteLine(cpt.Value); 

要存儲捕獲在一個數組,你可以使用下面的LINQ聲明:

var result = matches.Cast<Match>() 
        .SelectMany(m => m.Groups["num"].Captures.Cast<Capture>()) 
        .Select(c => c.Value).ToArray(); 
+0

這個工程就像一個魅力,我測試使用你的代碼和做一些調整。例如 - 添加附加數據並使用數組訪問附加數據。謝謝! – user2248001 2013-04-05 08:18:01

0

代替正則表達式的你可以考慮使用的方法是這樣的:

private IEnumerable<int> GetNumbers(string text) 
{ 
    var textParts = text.Split(new []{'(',')'}); 
    if (textParts.Length != 3) return new int[0]; 
    return textParts[1].Split(',').Select(n => Convert.ToInt32(n.Trim())); 
} 
0

試試這個:

string s = "add(2,3,1),4"; 

      MatchCollection matches = Regex.Matches(Regex.Matches(s, @"\(.*?\)").Cast<Match>().First().ToString(), @"\d+"); 
      string[] result = matches.Cast<Match>() 
             .Take(10) 
             .Select(match => match.Value) 
             .ToArray(); 

結果[0] = 2;結果1 = 3;結果[2] = 1;

Demo

+0

如果數據以逗號分隔,代碼是否將數據排序?原因在'string s =「add(2,3,1); 4」;'最後一個數字不是用逗號分隔,而是用分號分隔 – user2248001 2013-04-05 08:08:28

+0

@ user2248001 ::首先我得到了我後面的「()」區域「()」中的單獨號碼 – KF2 2013-04-05 08:15:43

相關問題