如何从Java中的另一个字符串中提取字符串模式(如IP地址)

时间:2014-08-19 07:10:41

标签: java string parsing

我有一个字符串,其中包含电子邮件标题的接收部分。它就像from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS

如何从此字符串中提取112.35.4.152

4 个答案:

答案 0 :(得分:1)

尝试对RegExp类使用Pattern方法。

String str = "from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS id ...";
Pattern pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
Matcher matcher = pattern.matcher(str);

if (matcher.find()) {
    System.out.println(matcher.group(0));
} else {
    System.out.println("No match.");
}

打印:

  

112.35.4.152

答案 1 :(得分:1)

使用String.indexOf("")找到[]索引,将这些索引值提供给String.substring()方法,然后提取子字符串。

String Str="from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS id";
System.out.println(Str.substring((Str.indexOf("[")+1), Str.indexOf("]")) );

编辑: - 请在您的问题中更具体一点,我在您的评论中读到[]中包含的IP地址未被保证,在这种情况下您需要使用正则表达式。

IPV4 IP地址的模式是

\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b

Reference(你也可以在这里找到IPV6的正则表达式)

这是一个适合您的小片段: -

 String ip_pattern ="\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b";
 String input="from abc.xyz.com [112.35.4.152](abc.xyz.com. by xx.yy.com with ESMTPS id ";
 Pattern pattern = Pattern.compile(ip_pattern);
 Matcher matcher = pattern.matcher(input);

 if (matcher.find()) {
     System.out.println(matcher.group());
  }
 else{
     System.out.println("No ip found in given input");
  }

答案 2 :(得分:0)

"from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS id ...".

通过查看您的String,您可以在[之后获得子字符串,并以]结束

String s = "from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx
                                                    .yy.com with ESMTPS id ...";
int startIndex=s.indexOf("[");
int endIndex=s.indexOf("]");
System.out.println(s.substring(startIndex+1,endIndex));

输出:

112.35.4.152

了解String#substring()

答案 3 :(得分:-1)

试试这个

String IPADDRESS_PATTERN = 
    "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

Pattern pattern = Pattern.compile(IPADDRESS_PATTERN);
Matcher matcher = pattern.matcher(ipString);
    if (matcher.find()) {
        return matcher.group();
    }
    else{
        return "0.0.0.0";
    }

Credits: Extract ip address from string in java