Java Regular Expression, all but

I would like to combine everything except *.xhtml . I have a servlet listening *.xhtml and I want another servlet to catch the rest. If I match Servlet Faces with everything ( * ), it explodes when processing icons, stylesheets, and anything that is not a face request.

Here is what I tried unsuccessfully.

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

Any ideas?

Thanks,

Walter

+6
java regex seam
source share
4 answers

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

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

This template matches any that does not 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. 
+13
source share

Not a regular expression, but why use it when you don't need to?

 String page = "blah.xhtml"; if( page.endsWith( ".xhtml" )) { // is a .xhtml page match } 
+7
source share

You can use the negative forward statement:

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

Please note that the above only matches if the input contains the extension (.something).

0
source share

At the end of your template, you miss the " $ " and the negative look of the propper (which the " (^()) " does not). Look at the special constructions part of the syntax .

The correct template is:

 .*(?<!\.xhtml)$ ^^^^-------^ This is a negative look-behind group. 

The regex testing tool is invaluable in situations where you usually rely on people to double check your expressions for you. Instead of writing your own, please use something like RegexBuddy on Windows or Reggy on Mac OS X. These tools have settings that let you choose the Java regular expression engine (or similar to work) for testing. If you need to test .NET expressions, try Expresso . In addition, you can simply use the Sun test-harness from your tutorials, but it is not so instructive to formulate new expressions.

0
source share

All Articles