查找从字符串中获取的关键字,并在字符串列表中查找

时间:2012-12-11 15:59:13

标签: c# regex vb.net

我有list个字符串,其中包含4个项目:

Orange Lemon Pepper Tomato

另外,我有一个String str,其中有一句话:

Today, I ate a tomato and an orange.

1)如何检查str是否有来自list的某些关键字?不考虑大写或小写字母,基本上捕获匹配的任何东西?

我尝试了这个,但它不起作用,因为它会寻找相同的单词。 list.Contains(str)

同样Dim result As String() = list.FindAll(str, Function(s) s.ToLower().Contains(str))但也没有用。

2)如果tomato中的单词tomatoesstr怎么办,我怎样才能检测到tomato部分并丢弃es部分?

有任何建议或想法吗?

6 个答案:

答案 0 :(得分:3)

var list = new string[] { "Orange", "Lemon", "Pepper", "Tomato" };
var str = "Today, I ate a tomato and an orange.";

使用LINQ和正则表达式,您可以检查字符串是否包含任何关键字:

list.Any(keyword => Regex.IsMatch(str, Regex.Escape(keyword), RegexOptions.IgnoreCase));

或获得匹配的关键字:

var matched = list.Where(keyword =>
                Regex.IsMatch(str, Regex.Escape(keyword), RegexOptions.IgnoreCase));
// "Orange", "Tomato"

BTW这将匹配tomatoesfootomato。如果您需要匹配单词的开头,则应稍微更改搜索模式:@"(^|\s)" + keyword

答案 1 :(得分:3)

如果区分大小写不是问题,您可以这样做:

List<string> test = new List<string>();
test.Add("Lemon");
test.Add("Orange");
test.Add("Pepper");
test.Add("Tomato");

string str = "Today, I ate a tomato and an orange.";

foreach (string s in test)
{
      // Or use StringComparison.OrdinalIgnoreCase when cultures are of no issue.
      if (str.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) > -1)
      {
          Console.WriteLine("Sentence contains word: " + s);
      }
}

Console.Read();

答案 2 :(得分:2)

Regex reg = new Regex("(Orange|lemon|pepper|Tomato)", RegexOptions.IgnoreCase | RegexOptions.Singleline);
MatchCollection mc = reg.Matches("Today, I ate tomatoes and an orange.");
foreach (Match mt in mc)
{
    Debug.WriteLine(mt.Groups[0].Value);
}

答案 3 :(得分:1)

使用list.Contains(str),您正在检查list是否包含整个字符串。您需要做些什么才能检查strlist中是否有单词是这样的:

foreach(var s in list)
{
     if(str.ToLower().Contains(s.ToLower()))
     {
          //do your code here
     }
}

这将遍历您的列表,并检查您的str,看看它是否在那里。它也将解决您的问题2.由于tomatotomatoes的一部分,它将通过该检查。 ToLower()部分使所有内容都小写,并且在您想忽略大小写时通常使用。

答案 4 :(得分:1)

Private Function stringContainsOneOfMany(ByVal haystack As String, ByVal needles As String()) As Boolean
    For Each needle In needles
        If haystack.ToLower.Contains(needle.ToLower) Then
            Return True
        End If
    Next
    Return False
End Function

使用:

    Dim keywords As New List(Of String) From {
        "Orange", "Lemon", "Pepper", "Tomato"}
    Dim str As String = "Today, I ate a tomato and an orange"
    If stringContainsOneOfMany(str, keywords.ToArray) Then
        'do something
    End If

答案 5 :(得分:1)

    Dim str As String = "Today, I ate a tomato and an orange"
    Dim sWords As String = "Orange Lemon Pepper Tomato"
    Dim sWordArray() As String = sWords.Split(" ")

    For Each sWord In sWordArray

        If str.ToLower.Contains(sWord.ToLower) Then
            Console.WriteLine(sWord)
        End If

    Next sWord