Java Regex String Replace Last replaceLast(String input, String regex, String replacement)

Here you can find the source of replaceLast(String input, String regex, String replacement)

Description

replace Last

License

Open Source License

Declaration

public static String replaceLast(String input, String regex, String replacement) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    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;
        }/*from w ww  .j  a va  2s .  c  o m*/
        int lastMatchStart;
        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();
    }
}

Related

  1. replaceLast(String foo, String regex, String replacement)
  2. replaceLast(String string, String regex, String replacement)