java - removing semi colon from a string if the string ends with it

后端 未结 12 1894
陌清茗
陌清茗 2020-12-29 08:20

I have a requirement in which I need to remove the semicolon if it is present at the end of the String(only at the end). I have tried the following code. But still it is not

12条回答
  •  猫巷女王i
    2020-12-29 09:19

    text.replaceAll(";", "");
    

    Since Strings in Java are immutable, so replaceALl() method doesn't do the in-place replacement, rather it returns a new modified string. So, you need to store the return value in some other string. Also, to match the semi-colon at the end, you need to use $ quantifier after ;

    text = text.replaceAll(";$", "");
    

    $ denotes the end of the string since you want to replace the last semi-colon..

    If you don't use $, it will replace all the ; from your strings..

    Or, for your job, you can simply use this, if you want to remove the last ;:

        if (text.endsWith(";")) {
            text = text.substring(0, text.length() - 1);
            System.out.println(text);
        }
    

    UPDATE: And, if there are more semi-colons at the end:

    text = text.replaceAll(";+$", "");
    

提交回复
热议问题