【发布时间】:2010-10-06 12:54:17
【问题描述】:
如何使用否定的lookbehind(或任何其他方法)正则表达式来忽略包含特定子字符串的字符串?
我已经阅读了之前的两个 stackoverflow 问题:
java-regexp-for-file-filtering
regex-to-match-against-something-that-is-not-a-specific-substring
它们是我想要的几乎...我的问题是字符串没有以我想要忽略的结尾。如果是这样,这将不是问题。
我感觉这与环视是零宽度的事实有关,并且在第二次通过字符串时匹配... 但是,我不太确定内部结构。
无论如何,如果有人愿意花时间解释一下,我将不胜感激。
这是一个我想忽略的输入字符串示例:
192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] "GET /FOO/BAR/HTTP/1.1" 200 2246
这是一个输入字符串的示例,我想保留它以供进一步评估:
192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] "GET /FOO/BAR/content.js HTTP/1.1" 200 2246
对我来说,关键是我想忽略任何在文档根默认页面之后的 HTTP GET。
以下是我的小测试工具,也是迄今为止我想出的最好的 RegEx。
public static void main(String[] args){
String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/ HTTP/1.1\" 200 2246";
//String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/content.js HTTP/1.1\" 200 2246";
//String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/content.js HTTP/"; // This works
//String inString = "192.168.1.10 - - [08/Feb/2009:16:33:54 -0800] \"GET /FOO/BAR/ HTTP/"; // This works
String inRegEx = "^.*(?:GET).*$(?<!.?/ HTTP/)";
try {
Pattern pattern = Pattern.compile(inRegEx);
Matcher matcher = pattern.matcher(inString);
if (matcher.find()) {
System.out.printf("I found the text \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(), matcher.start(), matcher.end());
} else {
System.out.printf("No match found.%n");
}
} catch (PatternSyntaxException pse) {
System.out.println("Invalid RegEx: " + inRegEx);
pse.printStackTrace();
}
}
【问题讨论】:
-
所以,您只对明确请求“文件”的内容(例如 /path/to/file.txt)感兴趣,而不是指向“目录”的内容(例如 /path/to /) 请求的 URI 是否以某些“扩展名”(在您的示例中为 .js)结尾?
-
第一个问题正确。我只想要“文件”而不是“目录”。文件名和扩展名无关紧要......只想忽略对文档根目录的请求
标签: java regex regex-negation