Reputation: 9745
If I have a IP address String like : 10.120.230.78
I would like to get 10.120.
out of it
But the parts of the address can change from 1 tot 3 numbers as we all know ...
1.1.1.1
to 255.255.255.255
so ....
I believe you can use a pattern, but I don't have an idea how to.
Upvotes: 2
Views: 5731
Reputation: 4867
The best way is String.split()
as already mentioned by amit.
E.g.
String[] ipAddressParts = ipAddress.split();
Also you can use
StringTokenizer stringTokenizer = new StringTokenizer( ipAddress, "." );
while ( stringTokenizer.hasMoreTokens() ) {
System.out.println( stringTokenizer.nextToken() );
}
java.util.Scanner
Upvotes: 1
Reputation:
ip.substring(0, ip.indexOf('.',ip.indexOf('.') + 1) + 1)
where ip
is the string holding the IP address.
Upvotes: 2
Reputation: 178411
assume you store your ip as a string called ip, you can use String.split()
to get an array of the parts:
String[] tokens = ip.split("\\.");
Upvotes: 12