Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace every character occurence but last

Tags:

java

Lets say I have a string of a.b.c.d. How do I write a method which will transform that string into abc.d ? Or is there any method available implementation out there ?

What I have tried so far

        int dotPlacing = propertyName.lastIndexOf(".");//12
        String modString = propertyName.replace(".", "");
        modString = modString.substring(0, dotPlacing-1) + "."+modString.substring(dotPlacing-1);

I am using that for writing Hibernate criteria. It works for user.country.name but not for user.country.name.ss. Havent tried for any other strings.

like image 462
abiieez Avatar asked Jan 22 '26 03:01

abiieez


2 Answers

You can extract substring form 0 to lastIndexOf('.'). In this substring replace all . to empty string. After that merge with subtring (from lastIndexOf . to end).

Something like:

String theString = "a.b.c.d";

String separator = ".";
String replacement = "";
String newString = theString.substring(0, theString.lastIndexOf(separator)).replaceAll(separator , replacement).concat(theString.substring(theString.lastIndexOf(separator)));

Assert.assertEquals("abc.d", newString);
like image 92
Areo Avatar answered Jan 23 '26 18:01

Areo


  String start = "a.b.c.d.wea.s";
  String regex = "\\.(?=.*\\.)";
  String end = start.replaceAll(regex, "");
  System.out.println(end);
like image 27
Hovercraft Full Of Eels Avatar answered Jan 23 '26 17:01

Hovercraft Full Of Eels