String filtering in Java

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());
    }

Tapestry redirections

It’ll soon be a year for me working in a project that uses Tapestry as one of its core technologies. I’ve learnt many interesting things and also faced some challenges to do certain specific stuff. Internet has always been a good help tool, and now it’s time to give back my little bit.

Tapestry features the class RedirectException to break the execution at any time and bring the user to the URL you want. But that exception expects an URL, and if you want to reach an existing Tapestry page, you need the corresponging URL for it.

Fortunately, this post in the Tapestry wiki at apache.org showed me how to get that URL for Tapestry3. But I also needed that exception to work for Tapestry4, so I had to investigate how to do the same think using the HiveMind registry. Finally, I got the class working and I’ve contributed it to the wiki where I found the Tapestry3 one.

I hope this to be useful!