Java Regex String Replace replace(String s, Pattern pattern, Function func)

Here you can find the source of replace(String s, Pattern pattern, Function func)

Description

replace

License

BSD License

Declaration

public static String replace(String s, Pattern pattern, Function<Matcher, String> func) 

Method Source Code

//package com.java2s;
/**/*  ww  w.j  a  v a  2 s .  com*/
 * Copyright (c) 2015, Hidekatsu Izuno <hidekatsu.izuno@gmail.com>
 *
 * This software is released under the 2 clause BSD License, see LICENSE.
 */

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

public class Main {
    public static String replace(String s, Pattern pattern, String rep) {
        return replace(s, pattern, (m) -> {
            return rep;
        });
    }

    public static String replace(String s, Pattern pattern, Function<Matcher, String> func) {
        Matcher m = pattern.matcher(s);
        if (m.find()) {
            StringBuilder sb = new StringBuilder((int) (s.length() * 1.5));
            int start = 0;
            do {
                if (start < m.start()) {
                    sb.append(s, start, m.start());
                }
                sb.append(func.apply(m));
                start = m.end();
            } while (m.find());
            if (start < s.length()) {
                sb.append(s, start, s.length());
            }
            return sb.toString();
        }
        return s;
    }
}

Related

  1. replace(String line, String regexp, String replacement)
  2. replace(String message, ResourceBundle bundle)
  3. replace(String operateOn[], String from, String to)
  4. replace(String original, CharSequence target, CharSequence replacement)
  5. replace(String pattern, String replace, String s)
  6. replace(String s, Properties p)
  7. replace(String s1, String s2, Pattern pattern)
  8. replace(String source, String prefix, String suffix, String prefixReplace, String suffixReplace)
  9. replace(String source, String search, String replace)