2016-03-15 40 views
1

我需要從每一行提取與逗號分隔的數字(C#)正則表達式的具體名單

test 35,1 35,2 35,3 35,4 35,5 

test2 35,1 35,2 35,3 35,4 35,5 

test3 35,1 35,2 35,3 35,4 35,5 


test 35,1 35,2 35,3 35,4 35,5 

test2 35,1 35,2 35,3 35,4 35,5 

test3 35,1 35,2 35,3 35,4 35,5 

我想有一組名爲test,將有兩場比賽

test 35,1 35,2 35,3 35,4 35,5 
test 35,1 35,2 35,3 35,4 35,5 

什麼到目前爲止,我已經achived: (?>test(?>(?<test>[\w\s,]+)\n)),而是選擇到最後一行的所有文本

感謝

+0

喜歡的東西[這裏](HTTP: //regexstorm.net/tester?p=(%3f%3etest%5cb(%3f%3e%5cs*(%3f%3ctest%3e%5cd%2b(%3f%3a%2c%5cd%2b)*) )%2b)中與I =測試++++ 35%2C1 ++++ 35%2C2 ++++ 35%2C3 ++++ 35%2C4 ++++ 35%2C5%0D%0atest2 +++ 35 %2C1 ++++ 35%2C2 ++++ 35%2 C3 ++++ 35%2C4 ++++ 35%2C5%0D%0atest3 +++ 35%2C1 ++++ 35%2C2 ++++ 35%2C3 ++++ 35%2C4 ++++ 35%2C5%0D%0atest ++++ 35%2C1 ++++ 35%2C2 ++++ 35%2C3 ++++ 35%2C4 ++++ 35%2C5%0D%0atest2 +++ 35 %2C1 ++++ 35%2C2 ++++ 35%2C3 ++++ 35%2C4 ++++ 35%2C5%0D%0atest3 +++ 35%2C1 ++++ 35%2C2 +++ + 35%2C3 ++++ 35%2C4 ++++ 35%2C5)? –

+0

救生員謝謝你能幫我做出與所有組測試test2和test3相同的正則表達式,以便我可以捕獲所有匹配 – user3430435

+0

你可以在'test'後添加'\ d *':( ?> test \ d * \ b(?> \ s *(? \ d +(?:,\ d +)*))+)' - 這些數字將全部在第2組捕獲集合中。 –

回答

1

你可以這樣命名你的捕獲組:(?<name>expression)。寫剩下的事情很簡單。從文字字符串test開始,後跟任何空格字符,以確保您不會捕獲test2test3。然後捕獲所有剩餘的字符以獲得行的剩餘部分。

(?<test>test\s.*) 

然後,您可以訪問您的命名組是這樣的:

var matches = Regex.Matches(input, @"(?<test>test\s.*)"); 
foreach(Match match in matches) 
{ 
    string result = match.Groups["test"].Value; 
} 
0

這裏是正則表達式,你可以利用:

(?<key>test\d*)\b(?>\s*(?<test>\d+(?:,\d+)*))+ 

regex demo here,該key命名組將舉行test +數字值和test組將保存密鑰後的所有數字在CaptureCollectionmatch.Groups["test"].Captures):

enter image description here

這裏是你展示如何檢索C#這些值的IDEONE演示:

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text.RegularExpressions; 


public class Test 
{ 
    public static void Main() 
    { 
     var strs = new List<string> { "test 35,1 35,2 35,3 35,4 35,5", 
     "test2 35,1 35,2 35,3 35,4 35,5", 
     "test3 35,1 35,2 35,3 35,4 35,5", 
     "test 35,1 35,2 35,3 35,4 35,5", 
     "test2 35,1 35,2 35,3 35,4 35,5", 
     "test3 35,1 35,2 35,3 35,4 35,5"}; 

     var pattern = @"(?<key>test\d*)\b(?>\s*(?<test>\d+(?:,\d+)*))+"; 
     foreach (var s in strs) 
     { 
      var match = Regex.Match(s, pattern, RegexOptions.ExplicitCapture); 
      if (match.Success) 
      {      // DEMO 
       var key = match.Groups["key"].Value; 
       var tests = match.Groups["test"].Captures.Cast<Capture>().Select(m => m.Value).ToList(); 
       Console.WriteLine(key); 
       Console.WriteLine(string.Join(", and ", tests)); 
      } 
     } 
    } 
} 

輸出:

test 
35,1, and 35,2, and 35,3, and 35,4, and 35,5 
test2 
35,1, and 35,2, and 35,3, and 35,4, and 35,5 
test3 
35,1, and 35,2, and 35,3, and 35,4, and 35,5 
test 
35,1, and 35,2, and 35,3, and 35,4, and 35,5 
test2 
35,1, and 35,2, and 35,3, and 35,4, and 35,5 
test3 
35,1, and 35,2, and 35,3, and 35,4, and 35,5