我正在尝试从 URL 中过滤掉专用网络 IP。
以前我有这段代码
if(!sCurrentLine.startsWith("192.168") && !sCurrentLine.startsWith("172.") && !sCurrentLine.startsWith("10.")&& !sCurrentLine.startsWith("127.0.0"))
数据示例
10.1.1.83/nagiosxi/
10.1.1.83/nagiosxi//rr.php?uid=18-c96b5fb53f9
127.0.0.1/tkb/internet/
172.18.20.200/cgi-bin/topstats.pl?submit_type=topstats&time=00:2
这是我的新代码
Pattern privateIp=Pattern.compile("(^127\\.0\\.0\\.1)|(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^192\\.168\\.)");
while((sCurrentLine=br.readLine())!=null)
{
Matcher pnm=privateIp.matcher(sCurrentLine);
if(!pnm.matches())
{
System.out.println("not match");
}
}
我正在考虑使用模式匹配。但是,Pattern.compile
不采用此正则表达式。
或者有没有什么函数可以处理私网IP。
对此有什么想法吗?
最佳答案
这只是一个猜测,但您是否有可能没有在表示模式的字符串中转义 \
因为
Pattern.compile("(^127\\.0\\.0\\.1)|(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^192\\.168\\.)");
对我来说编译得很好(尽管我还没有在任何数据上测试它)。
编辑后更新
我可以看到您正在使用 matches
方法来检查正则表达式是否位于行首。这不起作用,因为 matches
检查正则表达式是否匹配整个数据。尝试将此方法更改为 find
if (!pnm.find()) {
System.out.println("not match");
}
关于java - 关于私网IP过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18392894/