When I parse lines in text file, I want to check if a line contains abc*xyz
, where *
is a wildcard. abc*xyz
is a user input format.
You can generate Regex
and match using it
searchPattern = "abc*xyz";
inputText = "SomeTextAndabc*xyz";
public bool Contains(string searchPattern,string inputText)
{
string regexText = WildcardToRegex(searchPattern);
Regex regex = new Regex(regexText , RegexOptions.IgnoreCase);
if (regex.IsMatch(inputText ))
{
return true;
}
return false;
}
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern)
.Replace(@"\*", ".*")
.Replace(@"\?", ".")
+ "$";
}
Here is the source and Here is a similar issue
If asterisk is the only wildcard character that you wish to allow, you could replace all asterisks with .*?
, and use regular expressions:
var filter = "[quick*jumps*lazy dog]";
var parts = filter.Split('*').Select(s => Regex.Escape(s)).ToArray();
var regex = string.Join(".*?", parts);
This produces \[quick.*?jumps.*?lazy\ dog]
regex, suitable for matching inputs.
Demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With