Java Regex String Replace replace(String text, String[] searchStrings, String[] replacements)

Here you can find the source of replace(String text, String[] searchStrings, String[] replacements)

Description

Replace multiple search strings simultaneously

License

Open Source License

Parameter

Parameter Description
text the source text
searchStrings search strings to replace
replacements texts to replace the corresponding search strings

Return

new text with search strings replaced

Declaration

public static String replace(String text, String[] searchStrings, String[] replacements) 

Method Source Code


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

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;

public class Main {
    static final String ERR_NULL_PARAM = "none of the parameters should be null";
    static final String ERR_SEARCHSTRINGS_REPLACEMENTS_LENGTH_MISMATCH = "there must be the same number of search strings and replacements";
    static final String ERR_NULL_OR_EMPTY_SEARCHSTRING = "there must be no null element or empty search string";
    static final String ERR_NULL_REPLACEMENT = "there must be no null element in replacements";
    static final String ERR_DUPLICATE_SEARCHSTRINGS = "search strings must be distinct";

    /**//from   ww  w . j av a  2 s  . co  m
     * Replace multiple search strings simultaneously
     *
     * @param text          the source text
     * @param searchStrings search strings to replace
     * @param replacements  texts to replace the corresponding search strings
     * @return new text with search strings replaced
     */
    public static String replace(String text, String[] searchStrings, String[] replacements) {
        validateParams(text, searchStrings, replacements);

        if (searchStrings.length == 0) {
            return text;
        }

        Map<String, String> searchStringsToReplacements = zipToMap(searchStrings, replacements);
        // note: using StringBuffer because of match.appendReplacement
        StringBuffer buffer = new StringBuffer();
        Matcher matcher = buildPattern(searchStrings).matcher(text);
        while (matcher.find()) {
            String pattern = matcher.group();
            String replacement = searchStringsToReplacements.get(pattern);
            matcher.appendReplacement(buffer, replacement);
        }
        matcher.appendTail(buffer);
        return buffer.toString();
    }

    private static void validateParams(String text, String[] searchStrings, String[] replacements) {
        if (anyNull(new Object[] { text, searchStrings, replacements })) {
            throw new IllegalArgumentException(ERR_NULL_PARAM);
        }
        if (searchStrings.length != replacements.length) {
            throw new IllegalArgumentException(ERR_SEARCHSTRINGS_REPLACEMENTS_LENGTH_MISMATCH);
        }
        if (anyNullOrEmpty(searchStrings)) {
            throw new IllegalArgumentException(ERR_NULL_OR_EMPTY_SEARCHSTRING);
        }
        if (anyNull(replacements)) {
            throw new IllegalArgumentException(ERR_NULL_REPLACEMENT);
        }
        if (!allDistinct(searchStrings)) {
            throw new IllegalArgumentException(ERR_DUPLICATE_SEARCHSTRINGS);
        }
    }

    private static Map<String, String> zipToMap(String[] searchStrings, String[] replacements) {
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < searchStrings.length; ++i) {
            map.put(searchStrings[i], replacements[i]);
        }
        return map;
    }

    private static Pattern buildPattern(String[] searchStrings) {
        return Pattern.compile(Stream.of(searchStrings).map(Pattern::quote).collect(joining("|")));
    }

    private static boolean anyNull(Object[] args) {
        return Stream.of(args).anyMatch(Objects::isNull);
    }

    private static boolean anyNullOrEmpty(String[] strings) {
        return Stream.of(strings).anyMatch(x -> x == null || x.isEmpty());
    }

    private static boolean allDistinct(String[] strings) {
        return Stream.of(strings).distinct().count() == strings.length;
    }
}

Related

  1. replace(String string, String pattern, String replacement, boolean literal)
  2. replace(String text, Map vars, String prefix)
  3. replace(String text, String find, String match, boolean useRegex, boolean isCaseSensitive)
  4. replace(String text, String findPattern, String replacePattern)
  5. replace(String text, String targetText, String newText)
  6. replace(String val)
  7. replace(String value)
  8. replace_values(HashMap values, String str)
  9. replace_with_in(String aStringToReplace, String aNewString, String aString)