Reputation: 19
I need a search function like this: The function accepts all strings with many types of wildcards:
* or % >>> can replace one or more characters
# >>> used to replace a number
@ >>> used to replace an alphabet
? >>> used to replace a character (can be both number and alphabet)
As I know, in LINQ there are 3 functions for searching strings: StartsWith, EndsWith and Contains. In SQL query, there are 2 types of LIKE: % for one or more characters and _ for only one character. So, how can I solve this problem?
Thank you very much
Upvotes: 1
Views: 5978
Reputation: 1325
You could use regex and replace the wild cards with regex expressions. Here is an example.
IEnumerable<string> Search(IEnumerable<string> data, string q)
{
string regexSearch = q
.Replace("*", ".+")
.Replace("%", ".+")
.Replace("#", "\\d")
.Replace("@", "[a-zA-Z]")
.Replace("?", "\\w");
Regex regex = new Regex(regexSearch);
return data
.Where(s => regex.IsMatch(s));
}
Upvotes: 6