检查字符串是否包含子字符串列表并保存匹配的字符串

时间:2015-05-15 13:45:48

标签: c# string contains

这是我的情况:我有一个代表文字的字符串

string myText = "Text to analyze for words, bar, foo";   

要在其中搜索的单词列表

List<string> words = new List<string> {"foo", "bar", "xyz"};

我想知道最有效的方法(如果存在),以获取文本中包含的单词列表,如下所示:

List<string> matches = myText.findWords(words)

5 个答案:

答案 0 :(得分:7)

除了必须使用Contains方法之外,此查询中没有特殊分析。所以你可以试试这个:

string myText = "Text to analyze for words, bar, foo";

List<string> words = new List<string> { "foo", "bar", "xyz" };

var result = words.Where(i => myText.Contains(i)).ToList();
//result: bar, foo

答案 1 :(得分:5)

您可以使用$already_selected_course = $_SESSION['course_id']; Now the query should look like. $query = "SELECT course.id,course.title,course.credits,course.status FROM course WHERE course.id != $already_selected_course"; 并与两个集合相交:

HashSet<string>

答案 2 :(得分:2)

正则表达式解决方案

var words = new string[]{"Lucy", "play", "soccer"};
var text = "Lucy loves going to the field and play soccer with her friend";
var match = new Regex(String.Join("|",words)).Match(text);
var result = new List<string>();

while (match.Success) {
    result.Add(match.Value);
    match = match.NextMatch();
}

//Result ["Lucy", "play", "soccer"]

答案 3 :(得分:0)

想到你想要能够使用IF(ISERROR(MATCH(A1,$B$1:$B$8,0)),"",A1)的想法,你可以为String类做一个扩展方法来做你想要的。

myText.findWords(words)

用法:

public static class StringExtentions
{
    public static List<string> findWords(this string str, List<string> words)
    {
        return words.Where(str.Contains).ToList();
    }
}

结果:

  

foo,bar

答案 4 :(得分:0)

这是一个解释空格和标点符号的简单解决方案:

static void Main(string[] args)
{
    string sentence = "Text to analyze for words, bar, foo";            
    var words = Regex.Split(sentence, @"\W+");
    var searchWords = new List<string> { "foo", "bar", "xyz" };
    var foundWords = words.Intersect(searchWords);

    foreach (var item in foundWords)
    {
        Console.WriteLine(item);
    }

    Console.ReadLine();
}