3

I tried to implement wildcards search in my application using some algorithms (k-gram algorithm etc.), but it was very complex.

Until i found this code, and it works perfectly .. but i don't know how it get check and get results !

Code:

public static boolean wildCardMatch(String text, String pattern)
{
  return text.matches( pattern.replace("?", ".?").replace("*", ".*?") );
}

Does their anyone help me to knows how it work ? what's the idea of replace function?

Minions
  • 5,104
  • 5
  • 50
  • 91

2 Answers2

3

What you're speaking about is called the glob pattern.

In the Java world, the glob pattern is more often translated into a regex pattern.

In your scenario, the implementation is very basic: the replace method is used to replace all occurrences of ? into the regex equivalent .?. Then all occurences of * are replaced by .*?.

So if you have the following glob pattern: abc*.def, the regex will become abc.*?.def.

When the regex is finally ready, it is used to be checked against the variable text using the method matches. This latter method accepts a regex as input.

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
1

The method you are using is String.replace(CharSequence target, CharSequence replacement).

It takes two objects implementing CharSequence interface as parameters, which might be one of following:

  • CharBuffer
  • Segment
  • String

  • StringBuffer
  • StringBuilder

And replaces every occurence of first CharSequence with second CharSequence in a String.


In your case, if the pattern parameter would contain **??, the text.matches method would get .?.?.*?.*? as the input, and that's what the text parameter must've contain as well (in terms of regular expressions), in order to successfully match them and the method to return true.

To clarify:

Difference between .*? and .* for regex

Community
  • 1
  • 1
mkierc
  • 1,193
  • 2
  • 15
  • 28
  • if the text is yellow , and pattern is yel* .. it will take all chars before * in pattern and check if it could be replaced in text ?? or it it has the same in text and return true ? – Minions Dec 29 '15 at 17:11
  • 2
    If the pattern is `yel*`, it will be turned into `yel.*` by `replace` method, which will match `yellow`, as `.*` means `Any character, occuring 0 or more times`. Regular Expressions Cheat Sheet: http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/ – mkierc Dec 29 '15 at 17:15