查找字符串后的所有字符串出现次数

时间:2014-09-02 15:48:03

标签: c# regex string

这里需要一点点推动。我有一个包含

等数据的文件
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);

2 个答案:

答案 0 :(得分:0)

您可以查看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;                  
        }
     }
  }   

答案 1 :(得分:0)

我认为你说你想要没有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="")将与模式匹配,但不会将其包含在捕获