Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

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."
like image 340
Muhammad Umer Avatar asked Nov 27 '25 23:11

Muhammad Umer


1 Answers

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.

like image 131
Wiktor Stribiżew Avatar answered Nov 30 '25 12:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!