2016-03-15 35 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