replace 最后一个 java,java replaceLast()
Is there replaceLast() in Java? I saw there is replaceFirst().
EDIT: If there is not in the SDK, what would be a good implementation?
解决方案
It could (of course) be done with regex:
public class Test {
public static String replaceLast(String text, String regex, String replacement) {
return text.replaceFirst("(?s)"+regex+"(?!.*?"+regex+")", replacement);
}
public static void main(String[] args) {
System.out.println(replaceLast("foo AB bar AB done", "AB", "--"));
}
}
although a bit cpu-cycle-hungry with the look-aheads, but that will only be an issue when working with very large strings (and many occurrences of the regex being searched for).
A short explanation (in case of the regex being AB):
(?s) #
Is there replaceLast() in Java? I saw there is replaceFirst(). EDIT: If there is not in the SDK, what would be a good implementation? 解决方案 It could (of course) be done with regex: public class Test { public static String replaceLast(String text, String regex, String replacement) { return text.replaceFirst("(?s)"+regex+"(?!.*?"+regex+")", replacement); } public static void main(String[] args) { System.out.println(replaceLast("foo AB bar AB done", "AB", "--")); } } although a bit cpu-cycle-hungry with the look-aheads, but that will only be an issue when working with very large strings (and many occurrences of the regex being searched for). A short explanation (in case of the regex being AB): (?s) #