检查字符串元组列表是否按顺序出现在字符串中

时间:2015-03-14 17:46:23

标签: c# regex linq

我有一个元组列表,其中包含我想在我的文本文件对象(newFile)的Queue属性中检查的字符串组合。 Queue是一个名为Lines的字符串队列。

我不确定元组列表是否可行,但如果在任何行中找到任何元组的Item1和Item2(在Item1然后是Item2顺序),我只想要一个真实的结果。这是我最好的镜头,我无法弄清楚如何编写LINQ语句。

List<Tuple<string,string>> codes = new List<Tuple<string, string>>()
   {
      new Tuple<string, string>("01,", "02,"),
      new Tuple<string, string>("02,", "03,"),
      new Tuple<string, string>("03,", "88,"),
      new Tuple<string, string>("88,", "88,"),
      new Tuple<string, string>("89,", "90,")                 
   };

bool codesFound = newFile.Lines
                      .Any(Regex.Match(codes.Select(x => (x.Item1 + "(.*)" + x.Item2)));

2 个答案:

答案 0 :(得分:1)

这样的事情会让你得到你想要的结果:

bool found = newFile.Lines
    .Any(x => codes.Select(y => x.IndexOf(y.Item1) > -1 && x.IndexOf(y.Item2) > -1 
                            && x.IndexOf(y.Item1) < x.IndexOf(y.Item2)).Any(z => z));

答案 1 :(得分:1)

如果您想检查正则表达式方式,请执行以下操作:

bool codesFound = newFile.Lines.Any(p =>
              Regex.IsMatch(p, string.Join("|", codes.Select(x => x.Item1 + ".+" + x.Item2).ToList()))
              );

在这里,我将所有模式加入到单个字符串中,如01,.+02,|02,.+03, ...然后检查输入数组中是否有满足此条件的字符串。