Java Regular Expression, match everything but

Walter White picture Walter White · Jun 30, 2009 · Viewed 20k times · Source

I would like to match everything but *.xhtml. I have a servlet listening to *.xhtml and I want another servlet to catch everything else. If I map the Faces Servlet to everything (*), it bombs out when handling icons, stylesheets, and everything that is not a faces request.

This is what I've been trying unsuccessfully.

Pattern inverseFacesUrlPattern = Pattern.compile(".*(^(\\.xhtml))");

Any ideas?

Thanks,

Walter

Answer

rampion picture rampion · Jun 30, 2009

What you need is a negative lookbehind (java example).

String regex = ".*(?<!\\.xhtml)$";
Pattern pattern = Pattern.compile(regex);

This pattern matches anything that doesn't end with ".xhtml".

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NegativeLookbehindExample {
  public static void main(String args[]) throws Exception {
    String regex = ".*(?<!\\.xhtml)$";
    Pattern pattern = Pattern.compile(regex);

    String[] examples = { 
      "example.dot",
      "example.xhtml",
      "example.xhtml.thingy"
    };

    for (String ex : examples) {
      Matcher matcher = pattern.matcher(ex);
      System.out.println("\""+ ex + "\" is " + (matcher.find() ? "" : "NOT ") + "a match.");
    }
  }
}

so:

% javac NegativeLookbehindExample.java && java NegativeLookbehindExample                                                                                                                                        
"example.dot" is a match.
"example.xhtml" is NOT a match.
"example.xhtml.thingy" is a match.