1

我有一个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)如果单词tomatotomatoesstr,我怎样才能检测到该tomato部分并丢弃该es部分?

有什么建议或想法吗?

4

6 回答 6

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"

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

于 2012-12-11T16:07:03.157 回答
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();
于 2012-12-11T16:08:46.283 回答
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);
}
于 2012-12-11T16:11:59.500 回答
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
于 2012-12-11T16:11:19.667 回答
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
于 2012-12-11T16:11:52.303 回答
1

使用list.Contains(str),您正在检查它是否list包含整个字符串。你需要做的是检查是否str有单词list是这样的:

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

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

于 2012-12-11T16:06:41.457 回答