Regex in Where Linq ASP.NET

I wanted to know if the Regex rule can be used in a linq query. Indeed, I would like to know if the identifier contains the word "Download".

Test 1:

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

      

This format works

Test 2:

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

      

This does not work.

Thanks in advance for your answers.

+3


source to share


3 answers


Adding ^

both $

characters to the beginning and end of the regex means that the entire string must match, not just the substring. Technically your regex is not equivalent to a function Contains()

that will return true for a substring match.

Remove these two characters from your substring. Also you don't need upper and lower case letters, you can use the option instead IgnoreCase

.



You shouldn't use regex for such simple scenarios. If the only reason you are using Regex is because your string can use any combination of upper and lower case, check out this excellent post for a function Contains()

that might ignore the case for you. Alternatively, you can also call ToLower()

in LINQ:

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

      

+3


source


You have used the anchors, ^

(start of line) and $

(end of line), which require a complete line match. Also, there is no need to use character classes listing all letter cases, use the undefined flag unchanged .

If you want to use regex

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

      



A non-regex solution is considered the best approach :

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

      

See this SO thread for details .

+2


source


As explained in the microsoft docs , this is what you should do:

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

      

-1


source







All Articles