简体   繁体   English

用美元符号替换字符串中的最后一个点

[英]replace last dot in a string with a dollar sign

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.我想de.java_chess.javaChess.game.GameImpl$GameStatus

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?我怎样才能解决这个问题?

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 . StringBuilder对这些操作有一些很好的工具,例如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 (ie [^.] ) character and $ asserts position at the end of a line.您可以使用Positive Lookahead(?=([^.]*)$)其中([^.]*)匹配任意数量的非点(即[^.] )字符和$在末尾断言 position一条线。 You can check regex101.com for more explanation.您可以查看regex101.com以获得更多说明。

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: 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 : Output在线演示

de.java_chess.javaChess.game.GameImpl$GameStatus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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