Java Regular Expression, match everything but

情到浓时终转凉″ 提交于 2019-12-07 03:15:05

问题


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


回答1:


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.



回答2:


Not regular expresion, but why use that when you don't have to?

String page = "blah.xhtml";

if( page.endsWith( ".xhtml" ))
{
    // is a .xhtml page match
}       



回答3:


You could use the negative look-ahead assertion:

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

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




回答4:


You're really only missing a "$" at the end of your pattern and a propper negative look-behind (that "(^())" isn't doing that). Look at the special constructs part of the syntax.

The correct pattern would be:

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

A Regular Expression testing tool is invaluable in these situations when you normally would 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 allowing you to choose Java's regular expression engine (or a work-alike) for testing. If you need to test .NET expressions try Expresso. Also, you could just use Sun's test-harness from their tutorials, but it's not as instructive for forming new expressions.



来源:https://stackoverflow.com/questions/1061651/java-regular-expression-match-everything-but

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!