Skip to main content
added 219 characters in body
Source Link
Wiktor Stribiżew
  • 630.7k
  • 41
  • 501
  • 629

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.

You can use a regex for this:

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

Here is a sample program on TutorialsPoint.

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.

Source Link
Wiktor Stribiżew
  • 630.7k
  • 41
  • 501
  • 629

You can use a regex for this:

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

Here is a sample program on TutorialsPoint.