Is there any way to search patterns in strings in C#?
Something like Sql LIKE would be very useful.
Linq to SQL Like Operator
there are several good answers here. to summarize what is already here and correct: using contains, startswith, endswith are good answers for most needs. regular expressions are what you want for more advanced needs.
something that is not mentioned in these answers, though, is that for a collection of strings, linq can be used to apply these filters in a call to the where method.
Have your tried
"This is a string".Contains("string");
This is my implementation - it passes the tests and does the trick - you may want to change the replacement token if you're using three tildes in your statements:
private Regex LikeExpressionToRegexPattern(String likePattern)
{
var replacementToken = "~~~";
String result = likePattern.Replace("_", replacementToken)
.Replace("%", ".*");
result = Regex.Replace(result, @"\[.*" + replacementToken + @".*\]", "_");
result = result.Replace(replacementToken, ".");
return new Regex("^" + result + "$", RegexOptions.IgnoreCase);
}
Example:
// Define a test string.
string text = "Hello stackoverflow world";
string like = "%flow%";
// Define a regular expression and Find matches.
MatchCollection matches = LikeExpressionToRegexPattern(like).Matches(text);
//Result.
if (matches.Count > 0) {
//Yes
} else {
//No
}
Add a VB.NET DLL encapsulating the VB.NET Like Operator
public static bool Like(this string value, string pattern)
{
if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(pattern))
return false;
bool valid = true;
string[] words = pattern.Split("*");
int counter = words.Count();
for (int i = 0; i < counter; i++)
{
valid = valid && value.StartsWith(words[i]);
value = value.Substring(words[i].Length);
}
return valid;
}