Java正则表达式,但匹配所有内容

我想匹配除*.xhtml所有内容。 我有一个servlet听*.xhtml ,我想要另一个servlet来捕获其他所有东西。 如果我将Faces Servlet映射到所有东西( * ),它会在处理图标,样式表和所有非面孔请求时发生爆炸。

这是我一直尝试失败的原因。

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

有任何想法吗?

谢谢,

沃尔特

你需要的是一个消极的lookbehind ( java示例 )。

 String 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 = ".*(? 

所以:

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

不经常表达,但为什么在你不需要的时候使用它?

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

你可以使用负面的前瞻断言:

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

请注意,如果输入包含扩展名(.something),则上述内容仅匹配。

你真的只是在你的模式结束时错过了一个“ $ ”和一个propper negative look-behind(那个“ (^()) ”没有这样做)。 查看语法的特殊构造部分。

正确的模式是:

 .*(? 

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