2017-08-03 28 views
3

我想知道是否有可能在linq請求中使用Regex規則。 的確我想知道一個ID是否包含單詞「下載」。正則表達式在Where Linq ASP.NET

測試1:

foreach (var apiData in viewReturn.Where(x => x.ID.Contains("Download"))) 
    { 
    apiExterne.Add(apiData); 
    } 

這種格式的工作

測試2:

foreach (var apiData in viewReturn.Where(x => Regex.IsMatch(x.ID, "^[dD][oO][wW][nN][lL][oO][aA][dD]$"))) 
    { 
    apiExterne.Add(apiData); 
    } 

這一個不工作。

非常感謝您的回答。

+0

又是什麼「不工作」是什麼意思?它找不到匹配嗎?你有錯誤嗎? – JuanR

+0

你好@Space,歡迎來到SO! 「這個不起作用」是什麼意思?您能否詳細說明您的確切問題,並詳細說明您遇到的錯誤?另外,您可能對[如何詢問文檔](https://stackoverflow.com/help/how-to-ask)感興趣。 –

+0

您是否嘗試過簡化 - 其中(x => x!= nulll && Regex.IsMatch(x.ID.ToUpper(),「DOWNLOAD」))) - 如果您只想檢查它是否包含單詞下載 –

回答

3

^$字符添加到正則表達式的開始和結尾意味着整個字符串應該匹配,而不僅僅是一個子字符串。所以在技術上你的正則表達式不等於Contains()函數,它也會爲子串匹配返回true。

從您的子字符串中刪除這兩個字符。你也不需要大寫和小寫字母,你可以使用IgnoreCase選項。

你不應該使用正則表達式來處理這樣簡單的場景。如果您使用正則表達式的唯一原因是您的字符串可以使用大小寫的任意組合,請檢查this excellent post以獲取Contains()函數,該函數可以爲您忽略大小寫。或者,你也可以撥打ToLower()在LINQ:

foreach (var apiData in viewReturn.Where(x => x.ID.ToLower().Contains("download"))) 
2

您使用的錨,^(字符串的開始)和$(字符串的結尾),需要一個完整的字符串匹配。此外,沒有必要使用列出所有字母大小寫的字符類,請使用case insensitive regex flag

如果你想使用正則表達式使用

foreach (var apiData in viewReturn.Where(x => 
      Regex.IsMatch(x.ID, "download", RegexOptions.IgnoreCase))) 
{ 
    apiExterne.Add(apiData); 
} 

非正則表達式的解決方案被認爲是最好的辦法

foreach (var apiData in viewReturn.Where(x => 
      culture.CompareInfo.IndexOf(x, "download", CompareOptions.IgnoreCase) >= 0)) 
{ 
    apiExterne.Add(apiData); 
} 

this SO thread for details

-1

microsoft docs解釋說,這是你應該做的:

System.Text.RegularExpressions.Regex searchTerm = 
     new System.Text.RegularExpressions.Regex(@"^[dD][oO][wW][nN][lL][oO][aA][dD]$"); 
var queryMatching = 
     from item in viewReturn 
     let itemID = item.ID 
     let matches = searchTerm.Matches(itemID) 
     where matches.Count > 0 
     select new 
     { 
      id = item.ID, 
      apiData = from System.Text.RegularExpressions.Match match in matches 
          select match.Value 
     };