kevin
kevin

Reputation: 1

JAVA remove the last "*" in the string

I want to remove ONLY the last * in the string. For example, abc* should become abc. abc*d*d should become abc*dd.

I checked other solutions, I found:

parameter.replaceAll("a$", "b")

This will replace the last "a" by "b". However, when I change it to this it shows an error:

parameter.replaceAll("*$", "b")

I also tried:

parameter.replaceAll("\\*$", "b")

Upvotes: 0

Views: 85

Answers (4)

David542
David542

Reputation: 110257

Here you could use a greedy (.+) up to the (last occurrence of) * and it should remove what you want. For example:

(.+)\* (click to see it on regex101)

enter image description here

Upvotes: 1

Andreas
Andreas

Reputation: 159114

Instead of a performance-heavy regex, you can use lastIndexOf() and substring(), for better performance when used inside a tight loop.

int idx = parameter.lastIndexOf('*');
if (idx != -1)
    parameter = parameter.substring(0, idx).concat(parameter.substring(idx + 1));

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109567

parameter = parameter.replaceFirst("\\*$", "b");  // "aaa*" to "aaab"
parameter = parameter.replaceFirst("\\*([^*]*)$", "b$1"); // "aa*aa*aa" to "aa*aabaa"

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361710

parameter.replaceAll("[*]([^*]*)$", "$1")
//                    ^^^
//                     A ^^^^^^^
//                          B

Match an asterisk (A) followed by 0 or more non-asterisks (B). The parentheses surrounding B mean that string is captured as $1. The replacement string only contains $1, which means that effectively, the asterisk is erased.

Make sure to assign the result to a variable, or print it. replaceAll() doesn't modify parameter in place; it returns the modified string.

Upvotes: 0

Related Questions