2013-04-26 222 views
0

如何檢查我的文本是否包含任何數組內容作爲不是「發短信」的單詞?檢查一個字符串是否包含任何字符串數組元素

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

我發現這個代碼所以我該如何適應它?

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

也是正則表達式這個工作的最佳方法?或者我應該使用foreach循環?

+1

你需要在兩個數組要搜索的關鍵字('array1'和'array2')? – Channs 2013-04-26 07:08:54

+0

不,我不想同時搜索至少兩個陣列不在同一時間。 – Incognito 2013-04-26 07:24:16

回答

8

也是正則表達式,爲這項工作的最佳方法?

直到沒有其他乾淨,高效和可讀的方法,我才避免使用正則表達式,但這是我想象中的味道問題。

數組中的任何單詞是否是字符串中的單詞?您可以使用LINQ:

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

+1我同意不使用正則表達式,直到有必要 – 2013-04-26 07:10:37

+0

是的,我認爲Linq可以做到這一點,但我對Linq的知識是最小的..這將做我認爲的工作,非常感謝。 – Incognito 2013-04-26 07:17:24

+0

我不想連接2個數組的小更新。所以我只是用這個: bool arraysContains = array1.Any(w => words.Contains(w)); – Incognito 2013-04-26 07:37:49

1

如果你要檢查text是否包含任何字符串像array1數組,你可以嘗試這樣的:

text.Split(' ').Intersect(array1).Any() 
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); 
+0

此代碼不適合我的情況,我需要單詞匹配。如果我將文本更改爲「some1文本....」,它將是真實的。 – Incognito 2013-04-26 07:31:53

0

如果你的話可能是鄰近的報價,逗號等,而不僅僅是空間,你可以是一個不是更聰明只是用Split()

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