Java Regex: How to extract an ip address other than the last part from a string?
I am experimenting with websockets
and I want it to automatically connect to the local network from another computer to LAN
, and since there are 255 possible computers on the same network, I want it to try everything and then connect to whichever it can connect to the first. However, the first part of the IP address, 192.168.1. * , differs from the router settings.
I can get all the current IP of the machine, then I want to extract the front end.
for example
25.0.0.5 will become 25.0.0.
192.168.0.156 will become 192.168.0.
192.168.1.5 will become 192.168.1.
etc.
String Ip = "123.345.67.1";
//what do I do here to get IP == "123.345.67."
source to share
You can use a regular expression for this:
String Ip = "123.345.67.1";
String IpWithNoFinalPart = Ip.replaceAll("(.*\\.)\\d+$", "$1");
System.out.println(IpWithNoFinalPart);
Short explanation: (.*\\.)
- capturing group containing all characters up to the last .
(due to greedy quantifier match *
) \\d+
matches 1 or more digits and $
- end of line.
Here's a sample program at TutorialsPoint .
source to share
String Ip = "123.345.67.1";
String newIp = Ip.replaceAll("\\.\\d+$", "");
System.out.println(newIp);
Output:
123.345.67
Explanation:
\.\d+$
Match the character "." literally «\.»
Match a single character that is a "digit" «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of the string, or before the line break at the end of the string, if any «$»
Demo:
source to share
Just split the line with a period "." If the string is a valid IP address string, then you must have a String [] array with 4 parts, then you can only join the first 3 with a dot "." and have a "front end"
i.e.
String IPAddress = "127.0.0.1";
String[] parts = IPAddress.split(".");
StringBuffer frontPart = new StringBuffer();
frontPart.append(parts[0]).append(".")
.append(parts[1]).append(".")
.append(parts[2]).append(".");
source to share