Here you can find the source of replace(Pattern pattern, String src, Function
Parameter | Description |
---|---|
pattern | pattern |
src | source string |
handler | function which take matched part of source string and return replacement value, must never return null |
public static String replace(Pattern pattern, String src, Function<String, String> handler)
//package com.java2s; /*/*from w w w. j a va2 s. c o m*/ * Copyright 2016 Code Above Lab LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { /** * Replace string with pattern obtaining replacement values through handler function. <p/> * Note that it differ from usual Pattern behavior when it process replacement for group references, * this code do nothing with replacement. * @param pattern pattern * @param src source string * @param handler function which take matched part of source string and return replacement value, must never return null * @return result string */ public static String replace(Pattern pattern, String src, Function<String, String> handler) { StringBuilder sb = null; Matcher matcher = pattern.matcher(src); int pos = 0; while (matcher.find()) { if (sb == null) { // replacement can be a very rare operation, and we not need excess string buffer sb = new StringBuilder(); } String expr = matcher.group(); String replacement = handler.apply(expr); sb.append(src, pos, matcher.start()); sb.append(replacement); pos = matcher.end(); } if (sb == null) { return src; } sb.append(src, pos, src.length()); return sb.toString(); } }