java replaceLast()

2022-08-31 14:40:49

在Java中有吗?我看到有.replaceLast()replaceFirst()

编辑:如果SDK中没有,那么什么是好的实现?


答案 1

它(当然)可以用正则表达式来完成:

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", "--"));
    }
}

尽管前瞻有点耗费CPU周期,但这只有在处理非常大的字符串(以及许多正在搜索的正则表达式)时才会出现问题。

一个简短的解释(在正则表达式的情况下):AB

(?s)     # enable dot-all option
A        # match the character 'A'
B        # match the character 'B'
(?!      # start negative look ahead
  .*?    #   match any character and repeat it zero or more times, reluctantly
  A      #   match the character 'A'
  B      #   match the character 'B'
)        # end negative look ahead

编辑

很抱歉唤醒一个旧帖子。但这仅适用于非重叠实例。例如,返回 ,不是.replaceLast("aaabbb", "bb", "xx");"aaaxxb""aaabxx"

没错,可以按如下方式修复:

public class Test {

    public static String replaceLast(String text, String regex, String replacement) {
        return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
    }

    public static void main(String[] args) {
        System.out.println(replaceLast("aaabbb", "bb", "xx"));
    }
}

答案 2

如果您不需要正则表达式,这里有一个子字符串替代方案。

public static String replaceLast(String string, String toReplace, String replacement) {
    int pos = string.lastIndexOf(toReplace);
    if (pos > -1) {
        return string.substring(0, pos)
             + replacement
             + string.substring(pos + toReplace.length());
    } else {
        return string;
    }
}

测试用例:

public static void main(String[] args) throws Exception {
    System.out.println(replaceLast("foobarfoobar", "foo", "bar")); // foobarbarbar
    System.out.println(replaceLast("foobarbarbar", "foo", "bar")); // barbarbarbar
    System.out.println(replaceLast("foobarfoobar", "faa", "bar")); // foobarfoobar
}