Today I’ve needed to match strings in Java against a pattern similar to the ones used in filename matching. Java already has a String.matches()
method to test against a regular expression, but hasn’t one to match against more limited filename-like patterns (* and ? wildcards).
At first, I tought about implementing the matching by hand, comparing character to character, but soon found a quickier and simpler approach: transform the pattern into a regular expression. Maybe this source code could be useful for you:
private boolean matchFilter(String sample, String filter) { if (sample==null || filter==null) return true; StringBuffer f=new StringBuffer(".*"); for (StringTokenizer st=new StringTokenizer( filter,"%*",true); st.hasMoreTokens();) { String t=st.nextToken(); if (t.equals("?")) f.append("."); else if (t.equals("*")) f.append(".*"); else f.append(Pattern.quote(t)); } f.append(".*"); return sample.matches(f.toString()); }