找到字符串后的所有字符串出现

问题描述:

只需在这里稍微推一下。我有一个像找到字符串后的所有字符串出现

xyz buildinfo app_id="12345" asf 
sfsdf buildinfo app_id="12346" wefwef 
... 

我需要得到以下APP_ID =一个字符串数组数与数据的文件。下面的代码给我所有的匹配,我可以得到计数(Regex.Matches(text,searchPattern).Count)。但我需要将实际项目放入数组中。

string searchPattern = @"app_id=(\d+)"; 
       var z = Regex.Matches(text, searchPattern); 
+1

'新的正则表达式(是searchPattern).Match(文本).Captures'(或'.Groups') – knittl 2014-09-02 15:50:52

+0

你是否绝对需要正则表达式,或者你会同样使用字符串方法? – terrybozzio 2014-09-02 16:06:21

我觉得你说你希望在无APP_ID部分项目(编号)。你想用一个Positive Lookbehind

string text = @"xyz buildinfo app_id=""12345"" asf sfsdf buildinfo app_id=""12346"" wefwef"; 
string searchPattern = @"(?<=app_id="")(\d+)"; 
var z = Regex.Matches(text, searchPattern) 
       .Cast<Match>() 
       .Select(m => m.Value) 
       .ToArray(); 

(?<=app_id="")将匹配的模式,但不包括在捕获

+0

这工作得很好!但它会选择像app_id = 12345这样的字符串。我只需要这个号码。我如何更改RE。或者我应该在Select – mhn 2014-09-02 16:08:10

+0

上使用Replace,我发现问题。我仍然在使用我的同一个RE – mhn 2014-09-02 16:14:29

你可以看看documentation

引用它,你可以使用此代码:

string pattern = @"app_id=(\d+)"; 
    string input = "xyz buildinfo app_id="12345" asf sfsdf buildinfo app_id="12346" efwef"; 

    Match match = Regex.Match(input, pattern); 
    if (match.Success) { 
    Console.WriteLine("Matched text: {0}", match.Value); 
    for (int ctr = 1; ctr <= match.Groups.Count - 1; ctr++) { 
     Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value); 
     int captureCtr = 0; 
     foreach (Capture capture in match.Groups[ctr].Captures) { 
      Console.WriteLine("  Capture {0}: {1}", 
          captureCtr, capture.Value); 
      captureCtr += 1;     
     } 
    } 
    }