【问题标题】:Java Regular Expression, match everything butJava 正则表达式,匹配除
【发布时间】:2010-11-06 21:27:08
【问题描述】:

我想匹配除 *.xhtml 之外的所有内容。我有一个 servlet 正在监听 *.xhtml,我想要另一个 servlet 来捕获其他所有内容。如果我将 Faces Servlet 映射到所有内容 (*),它会在处理图标、样式表和所有不是面孔请求的内容时崩溃。

这是我一直在尝试的,但没有成功。

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

有什么想法吗?

谢谢,

沃尔特

【问题讨论】:

    标签: java regex seam


    【解决方案1】:

    您需要的是negative lookbehind (java example)。

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

    此模式匹配不以“.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.");
        }
      }
    }
    

    所以:

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

    【讨论】:

    • 不幸的是,这不起作用(经过测试确认);可能是因为否定的前瞻断言需要其他东西来前瞻!
    • 好的,当我发布上述评论时,答案已被编辑为否定的后视断言。但这也不起作用。
    • 是的,从 $ 向后看是正确的解决方案。我现在可以看到 :-)
    • Walter 在他的自我回复中说,正则表达式必须匹配整个字符串,就好像使用了 match() 而不是 find()。只需将 .* 添加到该正则表达式的前面,您就会得到最佳答案。
    【解决方案2】:

    不是正则表达式,但为什么在不需要时使用它?

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

    【讨论】:

      【解决方案3】:

      您可以使用否定的前瞻断言:

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

      请注意,上述内容仅在输入包含扩展名 (.something) 时才匹配。

      【讨论】:

      • 这也会失败“an.xhtml.example.document.txt”
      【解决方案4】:

      您实际上只是在模式末尾缺少一个“$”和一个适当的否定后视(“(^())”没有这样做)。查看the syntax特殊构造部分。

      正确的模式是:

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

      正则表达式测试工具在这些情况下非常有用,因为您通常需要人们为您仔细检查您的表达式。不要自己编写,请在 Windows 上使用 RegexBuddy 或在 Mac OS X 上使用 Reggy。这些工具的设置允许您选择 Java 的正则表达式引擎(或类似工作)进行测试。如果您需要测试 .NET 表达式,请尝试 Expresso。此外,您可以只使用 Sun 教程中的 test-harness,但它对形成新表达式没有那么有指导意义。

      【讨论】:

        猜你喜欢
        • 2011-03-30
        • 2011-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        相关资源
        最近更新 更多