检查字符串是否包含任何字符串数组元素

时间:2013-04-26 06:56:43

标签: c# regex string pattern-matching

如果我的文本包含任何数组内容而不是“发短信”的话,我如何检查我的文字?

string text = "some text here";
string[] array1 = { "text", "here" };
string[] array2 = { "some", "other" };

我在SO上找到了这个代码,我该如何适应它?

string regexPattern = string.Format(@"\b{0}\b", Regex.Escape(yourWord));
if (Regex.IsMatch(yourString, regexPattern)) {
    // word found
}

正则表达式是这项工作的最佳方法吗?或者我应该使用foreach循环?

4 个答案:

答案 0 :(得分:8)

  

正则表达式是这项工作的最佳方法吗?

我避免使用正则表达式,直到没有其他干净,高效和可读的方法,但这是我认为的品味问题。

数组中的任何单词是否都是字符串的单词?你可以使用Linq:

string[] words = text.Split();
bool arraysContains = array1.Concat(array2).Any(w => words.Contains(w));

答案 1 :(得分:1)

如果您要检查text是否包含array1数组中的任何字符串,您可以尝试这样做:

text.Split(' ').Intersect(array1).Any()

答案 2 :(得分:0)

试试这段代码:

string text = "some text here";

string[] array1 = { "text", "here" };
string[] array2 = { "some", "other" };

bool array1Contains = array1.Any(text.Contains);
bool array2Contains = array2.Any(text.Contains);

答案 3 :(得分:0)

如果你的单词可能与引号,逗号等相邻而不仅仅是空格,那么你可以比使用Split()更聪明

var words = Regex.Split(text, @"\W+");
bool anyFound = words
    .Intersect(array1.Union(array2), StringComparer.CurrentCultureIgnoreCase)
    .Any();
相关问题