簡體   English   中英

檢查字符串是否包含任何字符串數組元素

[英]Check if a string includes any of the string array elements

如何檢查我的文本是否包含任何非“文本”單詞的數組內容?

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循環?

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

在沒有其他干凈,有效和易讀的方法之前,我會避免使用正則表達式,但是我認為這只是一個口味問題。

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

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

如果要檢查text是否在諸如array1類的數組中包含任何字符串,則可以嘗試以下操作:

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

試試這個代碼:

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);

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM