【问题标题】:Check if List of Tuples of Strings appear in string in order检查字符串元组列表是否按顺序出现在字符串中
【发布时间】:2015-03-14 17:46:22
【问题描述】:

我有一个元组列表,其中包含我想在我的文本文件对象 (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)));

【问题讨论】:

    标签: c# regex linq


    【解决方案1】:

    以防万一你想检查正则表达式的方式,你在这里:

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

    在这里,我将所有模式连接成一个字符串,例如01,.+02,|02,.+03,...,然后检查输入数组中是否有任何字符串满足此条件。

    【讨论】:

    • 不错。所以管道字符是OR的正则表达式?是这样的吗?
    • 是的,管道代表 OR。此外,.* 可以替换为.+,以防Item1Item2 之间存在一些文本。
    • 谢谢。两者之间总会有一些文字。我应该使用 .+ 而不是 .* 吗?
    • .* 表示any character, 0 or more repetitions.+ 表示 any character, 1 or more repetitions。因此,如果中间必须有一些文本,则需要使用.+。我更新了答案。
    • 如果我需要在 Item1 和 Item2 之间至少说 10 个字符怎么办?
    【解决方案2】:

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

    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));
    

    【讨论】:

    • 太棒了。所以 x 代表其中一条线,y 代表其中一个元组,并且 1)我们检查两个 Item 的存在和 2)Item1 在 Item2 之前。所以 z 就是我们所说的如果上述返回 true 随时返回 true?
    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 2013-01-09
    • 2012-11-19
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多