正则表达式从字符串中的多个IP地址

时间:2011-11-29 16:02:19

标签: java regex

我有一个包含多个ip地址的字符串,如下所示:

 String header = "Received: from example.google.com ([192.168.0.1]) by example.google.com ([192.168.0.2]) with mapi; Tue, 30 Nov 2010 15:26:16 -0600";

我想使用正则表达式从中获取两个IP。到目前为止,我的代码看起来像这样

public String parseIPFromHeader(String header) {
    Pattern p = Pattern.compile("\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");
    Matcher m = p.matcher(header);
    boolean matchFound = m.find();

    System.out.println(matchFound);

    if (matchFound) {
         // Get all groups for this match
        for (int i=0; i<=m.groupCount(); i++) {
            // Get the group's captured text
            String groupStr = m.group(i);

            // Get the group's indices
            int groupStart = m.start(i);
            int groupEnd = m.end(i);

            // groupStr is equivalent to
            System.out.println(header.subSequence(groupStart, groupEnd));
        }
    }
}

但我永远不会得到匹配。我接近这个吗?感谢

2 个答案:

答案 0 :(得分:5)

您在点之前转义\个字符,但如果我没记错,您也需要在\b序列中将其转义,因此请将其替换为\\b

答案 1 :(得分:0)

如果您只需要IP地址,则可以大大简化您的正则表达式以匹配那些

"([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})" //not perfect, i know...

然后多次使用Matcher.find()查找字符串

中的所有匹配项
while(m.find()) {
    String ip = m.group(1) //the first group is at index 1, group 0 is the whole match. (Does not actually make any difference here)
}