replace last dot in a string with a dollar sign

Viewed 191

I would like to replace the last dot in the following string with a dollar sign, how can I do that?

de.java_chess.javaChess.game.GameImpl.GameStatus

I would like to have de.java_chess.javaChess.game.GameImpl$GameStatus instead.

I am using the following line of code to do so:

invokedMeth = invokedMeth.replaceAll("(.*)\\.(\\d+)$","$1$$2");

However, this doesn't work and I end up with the same original string that I had as an input. How can I fix this?

2 Answers

For this requirement, I would use a non-regex solution that can be easier to understand as well as more efficient.

StringBuilder invokedMethSb = new StringBuilder(invokedMeth);
invokedMethSb.setCharAt(invokedMethSb.lastIndexOf("."), '$');

invokedMeth = invokedMethSb.toString();  
/*de.java_chess.javaChess.game.GameImpl$GameStatus*/

StringBuilder has some good utils for these operations, such as setCharAt.


As a personal opinion, I prefer the following one:

char[] invokedArray = invokedMeth.toCharArray();
invokedArray[invokedMeth.lastIndexOf(".")]='$';

invokedMeth = new String(invokedArray);
/*de.java_chess.javaChess.game.GameImpl$GameStatus*/

Regex solution:

You can use the Positive Lookahead, (?=([^.]*)$) where ([^.]*) matches any number of non-dot (i.e. [^.]) character and $ asserts position at the end of a line. You can check regex101.com for more explanation.

public class Main {
    public static void main(String[] args) {
        String str = "de.java_chess.javaChess.game.GameImpl.GameStatus";
        str = str.replaceAll("\\.(?=([^.]*)$)", "\\$");
        System.out.println(str);
    }
}

Output:

de.java_chess.javaChess.game.GameImpl$GameStatus

A proper regular expression can also help with this replacement:

String withDot = "de.java_chess.javaChess.game.GameImpl.GameStatus";
 
String with$ = withDot.replaceFirst("(\\w+(\\.\\w+)*)(\\.(\\w+))", "$1\\$$4");
 
System.out.println(with$);

Output online demo:

de.java_chess.javaChess.game.GameImpl$GameStatus
Related