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 will become 25.0.0. will become 192.168.0. will become 192.168.1.



 String Ip  = "123.345.67.1";
 //what do I do here to get IP == "123.345.67."



source to share

4 answers

You can use a regular expression for this:

String Ip  = "123.345.67.1";
String IpWithNoFinalPart  = Ip.replaceAll("(.*\\.)\\d+$", "$1");


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 .



String Ip  = "123.345.67.1";
String newIp = Ip.replaceAll("\\.\\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 «$»





Instead of regex, you can use String.lastIndexOf('.')

to find the last point and String.substring(...)

to extract the first part like this:

String ip = "";
System.out.println(ip.substring(0, ip.lastIndexOf('.') + 1));
// prints 192.168.1.




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"


    String IPAddress = "";
    String[] parts = IPAddress.split(".");

    StringBuffer frontPart = new StringBuffer();




All Articles