简体   繁体   中英

Java Regex: How to extract ip address except the last part from the string?

I am experimenting with websockets and I want to make it connect to local network automatically from another computer on the LAN and since there are 255 possible computers on the same network I want it to try all and then connect to whichever it can connect to first. However, first part of an IP address, 192.168.1.* , is different based on router settings.

I can get the whole current IP address of the machine, then I want to extract the front part.

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.

and so on

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

You can use a regex for this:

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

A quick regex explanation: (.*\\\\.) is a capturing group that holds all characters up to the last . (due to greedy matching with * quantifier), \\\\d+ matches 1 or several digits, and $ is the end of string.

Here is a sample program on TutorialsPoint .

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:

http://ideone.com/OZs6FY

Instead of a regex you could make use of String.lastIndexOf('.') to find the last dot and String.substring(...) to extract the first part as follows:

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

Just split the string on the dot "." If the string is a valid IP Address string, then you should then have a String[] array with 4 parts, you can then join only the first 3 with a dot "." and have the "front part"

ie



    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(".");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM