Reputation: 5477
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?
Upvotes: 3
Views: 2318
Reputation: 1188
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
Upvotes: 1
Reputation: 35457
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.
Upvotes: 3