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

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

Description

Works like String.replaceFirst, but replaces the last instance instead.

License

Open Source License

Parameter

Parameter Description
string a parameter
regex a parameter
replacement a parameter

Declaration

public static String replaceLast(String string, 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 {
    /**/*from  w  w  w .  j a v a  2 s .  c o  m*/
     * Works like String.replaceFirst, but replaces the last instance instead.
     *
     * @param string
     * @param regex
     * @param replacement
     * @return
     */
    public static String replaceLast(String string, String regex, String replacement) {
        if (regex == null) {
            return string;
        }
        if (string == null) {
            return null;
        }
        if (regex.length() > string.length()) {
            //It can't be contained in here
            return string;
        }
        Matcher m = Pattern.compile(regex).matcher(string);
        int start = -1;
        int end = -1;
        while (m.find()) {
            start = m.start();
            end = m.end();
        }
        if (start == -1 || end == -1) {
            //Didn't find it, return the whole string
            return string;
        } else {
            return string.substring(0, start) + replacement + string.substring(end, string.length());
        }
    }
}

Related

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