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

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

Description

Sostituisce nella stringa foo l'ultima occorrenza della regex con replacement (es.

License

Apache License

Declaration

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

Method Source Code

//package com.java2s;
//License from project: Apache License 

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

public class Main {
    /**// w  w w.j  a  v  a 2s . co m
     * Sostituisce nella stringa foo l'ultima occorrenza della regex con replacement
     * (es. replaceLast("abc12def34gh", "\\p{Digit}++", "@")=>"abc12def@gh")
     */
    public static String replaceLast(String foo, String regex, String replacement) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(foo);
        int start = -1;
        int end = -1;
        //      String toReplace = null;
        while (m.find()) {
            start = m.start();
            end = m.end();
            //         toReplace = m.group();
        }
        if (start < 0) {
            return foo;
        }
        return foo.substring(0, start) + replacement + foo.substring(end);
        //      System.out.println(start);
        //      System.out.println(end);
        //      System.out.println(foo.substring(0, start));
        //      System.out.println(foo.substring(start, end));
        //      System.out.println(foo.substring(end));
        //      System.out.println(toReplace);
    }
}

Related

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