Here you can find the source of replace(String s, Pattern pattern, Function
public static String replace(String s, Pattern pattern, Function<Matcher, String> func)
//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; } }