【问题标题】:Check If String Contains Entry From List<String> And Return The Entry检查字符串是否包含来自 List<String> 的条目并返回该条目
【发布时间】:2014-04-06 14:04:52
【问题描述】:

假设我有一个List&lt;string&gt; colors

List<string> colors = new List<string> { "red", "blue", "yellow"};

我有一个要搜索的字符串。

string myString = "There is a red apple";

我想检查 myString 是否包含列表中的任何内容并返回搜索。

在这种情况下,程序应该在控制台中找到"red"并输出"red"

我可以使用Any() 来检查包含部分,但我怎样才能返回结果?

colors.Any(myString.Contains); //this only returns a bool I believe

上面的方法我用了一半,我怎么才能得到实际的结果?

--编辑--

可以安全地假设 myString 最多只包含来自 colors 的 1,并且匹配始终是全字匹配。

【问题讨论】:

  • 您要区分大小写还是不区分大小写?
  • @ErikPhilips 不区分大小写
  • 如果colors 包含“app”应该匹配,因为您的字符串在“apple”中有子字符串“app”?

标签: c# string list contains


【解决方案1】:

你可以Split你的字符串在空白处,然后使用Enumerable.Intersect,比如:

var matching = colors.Intersect(myString.Split());

上面将返回matching中的一项,即red

如果你想要不区分大小写,那么你可以这样做:

var matching = colors.Intersect(myString.Split(), 
                                StringComparer.InvariantCultureIgnoreCase);

编辑:如果您正在寻找部分匹配或多个单词匹配,那么您可以这样做:

List<string> colors = new List<string> { "red", "red apple", "yellow", "app" };
string myString = "There is a red apple";

var partialAllMatched =
    colors
       .Where(r => myString.IndexOf(r, StringComparison.InvariantCultureIgnoreCase) >=0);

这会让你返回:

red
red apple
app

【讨论】:

  • 这仅匹配myString中的整个单词,而不是多个单词子字符串或部分单词子字符串。目前尚不清楚这是否是预期的行为。
  • @Servy,从问题中的示例来看,我认为 OP 不希望获得部分单词匹配或多个单词匹配。
  • 从问题中的示例,即colors.Any(myString.Contains);,相反的可能性似乎更大。无论如何,他需要澄清其中任何一种用途才能确定。
【解决方案2】:

或者你可以使用:

var result = colors.FindAll(myString.Contains);

这会返回一个包含输出的数组。

【讨论】:

    【解决方案3】:

    我建议你在这个上尝试正则表达式搜索。

    使用或运算符和每种颜色构建搜索模式。像这样的“(红色|蓝色|黄色)”。不确定该模式是否与正则表达式语法匹配,但您明白了。

    然后在下一步让正则表达式使用您的模式并尝试将其与提供的文本匹配。在您的情况下,文本是 myString。

    这是一个例子:

    class TestRegularExpressions
    {
        static void Main()
        {
            string[] sentences = 
            {
                "C# code",
                "Chapter 2: Writing Code",
                "Unicode",
                "no match here"
            };
    
            string sPattern = "code";
    
            foreach (string s in sentences)
            {
                System.Console.Write("{0,24}", s);
    
                if (System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    System.Console.WriteLine("  (match for '{0}' found)", sPattern);
                }
                else
                {
                    System.Console.WriteLine();
                }
            }
    
            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
    
        }
    }
    /* Output:
               C# code  (match for 'code' found)
               Chapter 2: Writing Code  (match for 'code' found)
               Unicode  (match for 'code' found)
               no match here
    */
    

    【讨论】:

      【解决方案4】:

      没有看到LINQ Enumerable.Where的用法,所以这里是:

      var colors = new[] {"red", "blue", "white", "black"};
      const string str = "There is a red apple with black rocket.";
      
      var foundWords = colors.Where(str.Contains).ToList();
      

      【讨论】:

        猜你喜欢
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        • 2016-09-16
        • 2020-10-06
        • 2011-12-07
        • 2022-10-23
        • 2022-01-09
        • 2011-03-19
        相关资源
        最近更新 更多