I have a string that contains the receive part of an email header. It's like from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS
.
How can I extract 112.35.4.152
from this string?
I have a string that contains the receive part of an email header. It's like from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS
.
How can I extract 112.35.4.152
from this string?
Try to use RegExp approach with Pattern class.
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.");
}
Prints:
112.35.4.152
Use String.indexOf("")
to locate your [
and ]
indexes, supply those index values to String.substring()
method , and extract the 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("]")) );
Edit:- Please be more specific in your questions, I read in your comments that the ip address being enclosed in []
is not guranteed , in that case you need to use regex.
the pattern for IPV4 ip addresses is
\\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 (Also you can find regex for IPV6 here)
Here is a small snippet that should work for you:-
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");
}
"from abc.xyz.com (abc.xyz.com. [112.35.4.152]) by xx.yy.com with ESMTPS id ...".
By looking at your String
, you can just get a substring start after [
and end with ]
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));
Output:
112.35.4.152
Read about String#substring()
Try this
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";
}