java replaceLast()

JavaString

Java Problem Overview


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

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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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
}

Solution 3 - Java

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

replaceAll("pattern$", replacement);

Solution 4 - Java

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

Solution 5 - Java

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

Solution 6 - Java

Use StringUtils from apache:

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

Solution 7 - Java

No.

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

Solution 8 - Java

If the inspected string is so that

myString.endsWith(substringToReplace) == true

you also can do

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

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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

Solution 12 - Java

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

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCarlos BlancoView Question on Stackoverflow
Solution 1 - JavaBart KiersView Answer on Stackoverflow
Solution 2 - JavaBalusCView Answer on Stackoverflow
Solution 3 - JavaPhantomKidView Answer on Stackoverflow
Solution 4 - JavaMihir MathuriaView Answer on Stackoverflow
Solution 5 - JavaJoachim SauerView Answer on Stackoverflow
Solution 6 - JavaAlex EscuView Answer on Stackoverflow
Solution 7 - JavaThomasView Answer on Stackoverflow
Solution 8 - JavaWhimusicalView Answer on Stackoverflow
Solution 9 - JavaAvrDragonView Answer on Stackoverflow
Solution 10 - JavaMushyPeasView Answer on Stackoverflow
Solution 11 - JavaxhayView Answer on Stackoverflow
Solution 12 - JavaManoj LenkaView Answer on Stackoverflow