我有一个字符串,其中包含电子邮件标题的接收部分。它就像from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS
。
如何从此字符串中提取112.35.4.152
?
答案 0 :(得分:1)
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
答案 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";
}