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