Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching strings with wildcard

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.

like image 972
Robinson Avatar asked May 18 '15 09:05

Robinson


People also ask

How do you match a string with a wildcard?

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.

What is wild card pattern matching?

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 ...

Which operator is useful for matching string containing wildcard character and?

Built-in pattern matching provides a versatile tool for making string comparisons.


1 Answers

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")); 
like image 200
Dmitry Bychenko Avatar answered Oct 13 '22 01:10

Dmitry Bychenko