Java replaceLast() [Duplicate]

Is there replaceLast() in Java? I saw there is replaceFirst().

EDIT: If there is not in the SDK, what would be a good implementation?

1

12 Answers

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)     # 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

EDIT

Sorry to wake up an old post. But this is only for non-overlapping instances. For example .replaceLast("aaabbb", "bb", "xx"); returns "aaaxxb", not "aaabxx"

True, that could be fixed as follows:

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

If you don't need regex, here's a substring alternative.

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

Testcase:

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
}
2

use replaceAll and add a dollar sign right after your pattern:

replaceAll("pattern$", replacement);
1

You can combine StringUtils.reverse() with String.replaceFirst()

1

See for yourself: String

Or is your question actually "How do I implement a replaceLast()?"

Let me attempt an implementation (this should behave pretty much like replaceFirst(), so it should support regexes and backreferences in the replacement String):

public static String replaceLast(String input, String regex, String replacement) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(input);
    if (!matcher.find()) {
       return input;
    }
    int lastMatchStart=0;
    do {
      lastMatchStart=matcher.start();
    } while (matcher.find());
    matcher.find(lastMatchStart);
    StringBuffer sb = new StringBuffer(input.length());
    matcher.appendReplacement(sb, replacement);
    matcher.appendTail(sb);
    return sb.toString();
}
4

Use StringUtils from apache:

org.apache.commons.lang.StringUtils.chomp(value, ignoreChar);
2

No.

You could do reverse / replaceFirst / reverse, but it's a bit expensive.

3

If the inspected string is so that

myString.endsWith(substringToReplace) == true

you also can do

myString=myString.replaceFirst("(.*)"+myEnd+"$","$1"+replacement) 
1

it is slow, but works:3

    import org.apache.commons.lang.StringUtils;

public static String replaceLast(String str, String oldValue, String newValue) {
    str = StringUtils.reverse(str);
    str = str.replaceFirst(StringUtils.reverse(oldValue), StringUtils.reverse(newValue));
    str = StringUtils.reverse(str);
    return str;
}

split the haystack by your needle using a lookahead regex and replace the last element of the array, then join them back together :D

String haystack = "haystack haystack haystack";
String lookFor = "hay";
String replaceWith = "wood";

String[] matches = haystack.split("(?=" + lookFor + ")");
matches[matches.length - 1] = matches[matches.length - 1].replace(lookFor, replaceWith);
String brandNew = StringUtils.join(matches);

I also have encountered such a problem, but I use this method:

public static String replaceLast2(String text,String regex,String replacement){
    int i = text.length();
    int j = regex.length();

    if(i<j){
        return text;
    }

    while (i>j&&!(text.substring(i-j, i).equals(regex))) {
        i--;
    }

    if(i<=j&&!(text.substring(i-j, i).equals(regex))){
        return text;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(text.substring(0, i-j));
    sb.append(replacement);
    sb.append(text.substring(i));

    return sb.toString();
}

It really works good. Just add your string where u want to replace string in s and in place of "he" place the sub string u want to replace and in place of "mt" place the sub string you want in your new string.

import java.util.Scanner;

public class FindSubStr 
{
 public static void main(String str[])
 {
    Scanner on=new Scanner(System.in);
    String s=on.nextLine().toLowerCase();
    String st1=s.substring(0, s.lastIndexOf("he"));
    String st2=s.substring(s.lastIndexOf("he"));
    String n=st2.replace("he","mt");

    System.out.println(st1+n);
 }

}
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest