Java正则表达式,匹配除 [英] Java Regular Expression, match everything but
本文介绍了Java正则表达式,匹配除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想匹配除 *.xhtml
之外的所有内容.我有一个 servlet 正在侦听 *.xhtml
并且我想要另一个 servlet 来捕获其他所有内容.如果我将 Faces Servlet 映射到所有内容 (*
),它会在处理图标、样式表和所有不是人脸请求的内容时爆炸.
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))");
有什么想法吗?
谢谢,
沃尔特
推荐答案
What you need is a negative lookbehind (java example).
String regex = ".*(?<!\\.xhtml)$";
Pattern pattern = Pattern.compile(regex);
此模式匹配不以.xhtml"结尾的任何内容.
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.");
}
}
}
所以:
% javac NegativeLookbehindExample.java && java NegativeLookbehindExample
"example.dot" is a match.
"example.xhtml" is NOT a match.
"example.xhtml.thingy" is a match.
这篇关于Java正则表达式,匹配除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文