检查word是否包含字符串列表中的子字符串

时间:2015-02-17 16:18:47

标签: c# regex linq

我已经看过使用linq这样做的例子:

List<string> list = new List<string> {"One", "Two", "Three", "Four", "five", "six" };
string text = "OneTwoThreeFour";

list.Any(s => text.contains(s))

但是这适用于所有可能的单词吗?意思是,如果我有一个由3个较小的单词组成的大单词(没有被任何特殊字符分隔),它会捕获所有3个子单词吗?或者一旦找到匹配就停止检查?

我想要完成的是采用"OneTwoThreeFour"之类的字词,并在每个唯一字之间添加一个空格或短划线,使其为"One Two Three Four"

有更好的方法吗?

是否可以获得作为匹配返回的“字符串”?

2 个答案:

答案 0 :(得分:1)

更新以涵盖任一条件:

您可以通过adding spaces before capital letters获取text中的字词列表,然后拆分空格。然后,您可以使用list将结果与SequenceEqual()进行比较。

以下是一个例子:

static void Main(string[] args)
{
    List<string> list = new List<string> {"One", "Two", "Three", "Four", "Five" };
    string text = "OneTwoThreeFourFive";

    string withSpaces = AddSpacesToSentence(text, true);
    List<string> list2 = withSpaces.Split(' ').ToList();

    bool b = list.SequenceEqual(list2);
}

// Refer to: https://stackoverflow.com/a/272929/4551527
static string AddSpacesToSentence(string text, bool preserveAcronyms)
{
    if (string.IsNullOrWhiteSpace(text))
        return string.Empty;
    StringBuilder newText = new StringBuilder(text.Length * 2);
    newText.Append(text[0]);
    for (int i = 1; i < text.Length; i++)
    {
        if (char.IsUpper(text[i]))
            if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
                (preserveAcronyms && char.IsUpper(text[i - 1]) &&
                    i < text.Length - 1 && !char.IsUpper(text[i + 1])))
                newText.Append(' ');
        newText.Append(text[i]);
    }
    return newText.ToString();
}

请注意,我从这个答案得到了AddSpacesToSentence的实现:https://stackoverflow.com/a/272929/4551527

另一次更新

顺便说一句,如果列表中单词的顺序不重要(换句话说:“OneTwo”应该匹配{“Two”,“One”}),那么你可以Sort()这两个列表在执行SequenceEquals()

之前

原创(当我认为是单向比较时)

您可以改为使用All()

List<string> list = new List<string> {"One", "Two", "Three", "Four" };
string text = "OneTwoThreeFour";

list.All(s => text.Contains(s))

如果序列中的所有元素都满足谓词(此处为contains),则返回true。

上面的代码片段返回true。如果您向list添加“五”(但保持text相同),则会返回false。

答案 1 :(得分:1)

一种简单的方法可能是遍历项目列表并执行String Replace (我使用过StringBuilder,您也可以使用String.Replace像:

List<string> list = new List<string> { "One", "Two", "Three", "Four", "five", "six" };
string text = "OneTwoThreeFour";
StringBuilder sb = new StringBuilder(text);
foreach (var str in list)
{
    sb.Replace(str, " " + str + " ");
}

string modifiedText = sb.ToString();

那会给你modifiedText = " One Two Three Four "。作为附注,您不必检查列表中是否存在Any项。如果该项目不在列表中,String.Replace将不会执行任何操作。

有关:

  

会抓住所有3个子词吗?或者这会停止检查一次   发现一场比赛?

一旦找到匹配,它将停止。您正在使用Enumerable.Any,一旦找到匹配项,就不会进行进一步的比较。