I'm trying to make a little chat program for experimentation, but seeing as I'm not the best Java programmer, I don't know how to separate a port from an IP where they are both in the same string.
This isn't super clear, but here's basically what I want to do. User enters IP and port in IP:Port format Scanner grabs it and puts it into a String Somehow put everything before the colon into a string and all numbers after the colon into an int.
Any ideas on how to do this?
First, you should check if the
String
contains a colon. Then, you can useString.split(String)
andInteger.parseInt(String)
with something likeOutput is
You can use pattern matcher in java to get the address and the port information and by the way you can validate the input string as well.
You can have multiple regular expression to validate V4 and V6 addresses. Hope this would help.
Use String.split
IP = splittedIP[0], Port = splittedIP[1] in String
you will need Integer.parseInt to get the integer value of port
to validate IP:PORT format you may try this:
thanks to frb and mkyong :)
and to separate ip and port :
In this case,
address
will be"127.0.0.1"
andport
will be theint
999
.Note that
Integer.parseInt
will throw aNumberFormatException
in this case if the portion of the string after the:
cannot be parsed as an integer, as in"127.0.0.1:blahblah"
. As well, if the string does not contain a:
there will be noparts[1]
.