我正在尝试匹配Java中没有.jsp/.jspx扩展名的字符串,并且在使用负面先行模式时遇到了很多困难。
给定一串字符串:
String string1 = "templateName";
String string2 = "some/path"
String string3 = "basic/filename/no/extension"
String string4 = "some/path/to/file.jsp"
String string5 = "alternative/path/to/file.jspx"我正在尝试找到一个匹配前3个而不是后2个的正则表达式。
我本以为具有负向先行的正则表达式是可行的。
例如:
Pattern p = new Pattern.compile( "(.+)(?!\\.jsp[x]?)")但该模式似乎与上述所有字符串都匹配。我最初认为第一组可能太贪婪了,所以我尝试了(.+?),但这也没有帮助。
这个SO Post很好地解释了负向先行,但不幸的是它不能帮助我找到正确的组合。
我是不是漏掉了什么明显的东西?
发布于 2013-10-29 03:20:16
您可以将negative lookbehind用作:
Pattern p = new Pattern.compile( "^(.+)(?<!\\.jspx?)$" );或者您可以像这样使用negative lookahead:
Pattern p = new Pattern.compile( "^(?!.+?\\.jspx?$)(.+)$" );发布于 2013-10-29 13:45:17
下面是另一个负面回顾:
Pattern p = new Pattern.compile(".*(?<!.jspx?)$");(?<!.jspx?)是一个被取反的lookbehind断言,这意味着在字符串的末尾之前,没有.jsp或.jspx
您正在查看字符串$的末尾
参考资料:
http://www.regular-expressions.info/lookaround.html
https://stackoverflow.com/questions/19643239
复制相似问题