我将如何使用负向后查找(或任何其他方法)正则表达式来忽略包含特定子字符串的字符串?
我读过之前的两个 stackoverflow 问题:
java-正则表达式用于文件过滤 https://stackoverflow.com/questions/367862/java-regexp-for-file-filtering
正则表达式匹配非特定子字符串的内容 https://stackoverflow.com/questions/42990/regex-to-match-against-something-that-is-not-a-specific-substring
他们是nearly我想要什么...我的问题是字符串没有以我想忽略的内容结尾。如果这样做的话,这就不成问题了。
我有一种感觉,这与环视为零宽度以及第二次通过字符串时某些内容匹配的事实有关......
但是,我不太确定内部结构。
无论如何,如果有人愿意花时间解释它,我将不胜感激。
这是我想忽略的输入字符串的示例:
192.168.1.10 - - [08/2/2009:16:33:54 -0800]“获取/FOO/BAR/HTTP/1.1”200 2246
以下是我想保留以供进一步评估的输入字符串示例:
192.168.1.10 - - [08/2/2009:16:33:54 -0800]“获取/FOO/BAR/content.js HTTP/1.1”200 2246
对我来说,关键是我想忽略文档根默认页面之后的任何 HTTP GET。
以下是我的小测试工具和迄今为止我想出的最好的正则表达式。
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();
}
}