Java Regex String Replace replace(String str, String replacement, Function func)

Here you can find the source of replace(String str, String replacement, Function func)

Description

replace

License

Open Source License

Parameter

Parameter Description
str a parameter
replacement a parameter
func a parameter

Declaration

public static String replace(String str, String replacement, Function<Matcher, String> func) 

Method Source Code


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

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

public class Main {
    /**//from ww w  .j a v  a  2s  .  c  om
     *
     * @param str
     * @param replacement
     * @param func
     * @return
     */
    public static String replace(String str, String replacement, Function<Matcher, String> func) {
        return replace(str, replacement, func, 0);
    }

    /**
     *
     * @param str
     * @param replacement
     * @param func
     * @param flags
     * @return
     */
    public static String replace(String str, String replacement, Function<Matcher, String> func, int flags) {
        if (str == null || str.isEmpty())
            return str;
        Pattern p = Pattern.compile(replacement, flags);
        Matcher m = p.matcher(str);
        boolean result = m.find();
        StringBuffer sb = new StringBuffer();
        do {
            String res = func.apply(m);
            m.appendReplacement(sb, res);
            result = m.find();
        } while (result);
        m.appendTail(sb);

        return sb.toString();
    }
}

Related

  1. replace(String source, String prefix, String suffix, String prefixReplace, String suffixReplace)
  2. replace(String source, String search, String replace)
  3. replace(String source, String search, String replacement)
  4. replace(String source, String[] patterns, String[] replacements)
  5. replace(String str, String key, String value)
  6. replace(String string, Pattern pattern, String replacement)
  7. replace(String string, Pattern[] patterns, String[] replacements)
  8. replace(String string, Properties table)
  9. replace(String string, String pattern, String replacement, boolean literal)