[英]JAVA remove the last "*" in the string
I want to remove ONLY the last * in the string.我只想删除字符串中的最后一个 *。 For example, abc*
should become abc
.例如, abc*
应该变成abc
。 abc*d*d
should become abc*dd
. abc*d*d
应该变成abc*dd
。
I checked other solutions, I found:我检查了其他解决方案,我发现:
parameter.replaceAll("a$", "b")
This will replace the last "a" by "b".这将用“b”替换最后的“a”。 However, when I change it to this it shows an error:但是,当我将其更改为此时,它会显示错误:
parameter.replaceAll("*$", "b")
I also tried:我也试过:
parameter.replaceAll("\\*$", "b")
parameter = parameter.replaceFirst("\\*$", "b"); // "aaa*" to "aaab"
parameter = parameter.replaceFirst("\\*([^*]*)$", "b$1"); // "aa*aa*aa" to "aa*aabaa"
Instead of a performance-heavy regex, you can use lastIndexOf()
and substring()
, for better performance when used inside a tight loop.您可以使用lastIndexOf()
和substring()
代替性能繁重的正则表达式,以便在紧密循环中使用时获得更好的性能。
int idx = parameter.lastIndexOf('*');
if (idx != -1)
parameter = parameter.substring(0, idx).concat(parameter.substring(idx + 1));
parameter.replaceAll("[*]([^*]*)$", "$1")
// ^^^
// A ^^^^^^^
// B
Match an asterisk (A) followed by 0 or more non-asterisks (B).匹配星号 (A) 后跟 0 个或多个非星号 (B)。 The parentheses surrounding B mean that string is captured as $1
. B 周围的括号表示字符串被捕获为$1
。 The replacement string only contains $1
, which means that effectively, the asterisk is erased.替换字符串仅包含$1
,这意味着实际上删除了星号。
Make sure to assign the result to a variable, or print it.确保将结果分配给变量,或打印它。 replaceAll()
doesn't modify parameter
in place; replaceAll()
不会就地修改parameter
; it returns the modified string.它返回修改后的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.