I would like to match strings with a wildcard (*), where the wildcard means "any". For example:
*X = string must end with X X* = string must start with X *X* = string must contain X
Also, some compound uses such as:
*X*YZ* = string contains X and contains YZ X*YZ*P = string starts with X, contains YZ and ends with P.
Is there a simple algorithm to do this? I'm unsure about using regex (though it is a possibility).
To clarify, the users will type in the above to a filter box (as simple a filter as possible), I don't want them to have to write regular expressions themselves. So something I can easily transform from the above notation would be good.
wildcard character can match any character in the input string, and the * wildcard character can match to zero or more characters in the input string. Input: string = XYXZZXY, pattern = X***X? The idea is to solve this problem by dividing the problem into subproblems recursively.
Wildcard Pattern Matching: Given a string and a pattern containing wildcard characters, i.e., * and ? , where ? can match to any single character in the string and * can match to any number of characters including zero characters, design an efficient algorithm to check if the pattern matches with the complete string or ...
Built-in pattern matching provides a versatile tool for making string comparisons.
Often, wild cards operate with two type of jokers:
? - any character (one and only one) * - any characters (zero or more)
so you can easily convert these rules into appropriate regular expression:
// If you want to implement both "*" and "?" private static String WildCardToRegular(String value) { return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; } // If you want to implement "*" only private static String WildCardToRegular(String value) { return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$"; }
And then you can use Regex as usual:
String test = "Some Data X"; Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X")); Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*")); Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*")); // Starts with S, ends with X, contains "me" and "a" (in that order) Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));
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