我想匹配除*.xhtml
. 我有一个 servlet 正在监听*.xhtml
,我想要另一个 servlet 来捕获其他所有内容。*
如果我将Faces Servlet 映射到所有内容(
这是我一直在尝试的,但没有成功。
Pattern inverseFacesUrlPattern = Pattern.compile(".*(^(\\.xhtml))");
有任何想法吗?
谢谢,
沃尔特
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.
不是正则表达式,但为什么在不需要时使用它?
String page = "blah.xhtml";
if( page.endsWith( ".xhtml" ))
{
// is a .xhtml page match
}
您可以使用否定的前瞻断言:
Pattern inverseFacesUrlPattern = Pattern.compile("^.*\\.(?!xhtml).*$");
请注意,仅当输入包含扩展名 (.something) 时,上述内容才匹配。
您实际上只是$
在模式的末尾缺少一个 " " 和一个适当的否定后视(那个 " (^())
" 没有这样做)。查看语法的特殊构造部分。
正确的模式是:
.*(?<!\.xhtml)$
^^^^-------^ This is a negative look-behind group.
在这些情况下,当您通常需要人们为您仔细检查您的表达式时,正则表达式测试工具非常有用。不要自己编写,而是在 Windows 上使用RegexBuddy或在 Mac OS X 上使用Reggy。这些工具的设置允许您选择 Java 的正则表达式引擎(或类似工作)进行测试。如果您需要测试 .NET 表达式,请尝试Expresso。此外,您可以只使用 Sun 在他们的教程中的测试工具,但它对形成新表达式没有那么有指导意义。