Is there any way to search patterns in strings in C#?
Something like Sql LIKE would be very useful.
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
}