Android String Replace replace(String str, Map replacementMap)

Here you can find the source of replace(String str, Map replacementMap)

Description

replace

Declaration

public static String replace(String str,
            Map<String, Object> replacementMap) 

Method Source Code

//package com.java2s;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONObject;

public class Main {
    /**//from w  w w.  j  a v  a  2 s  .c om
     * Replaces {propname} matches in the string with the corresponding object.toString
     */
    private static final Pattern REPLACE_PATTERN = Pattern
            .compile("([^\\\\]|^)\\{(.+?)\\}");

    public static String replace(String str,
            Map<String, Object> replacementMap) {
        Matcher matcher = REPLACE_PATTERN.matcher(str);

        //populate the replacements map ...
        StringBuilder builder = new StringBuilder();
        int i = 0;
        while (matcher.find()) {
            Object replacement = replacementMap.get(matcher.group(2));
            builder.append(str.substring(i, matcher.start() == 0 ? 0
                    : matcher.start() + 1));
            builder.append(replacement != null ? replacement : "");
            i = matcher.end();
        }
        builder.append(str.substring(i, str.length()));

        String result = builder.toString();
        result = result.replace("\\{", "{");
        result = result.replace("\\}", "}");

        return result;
    }

    public static String replace(String str, JSONObject replacementMap) {
        Matcher matcher = REPLACE_PATTERN.matcher(str);

        //populate the replacements map ...
        StringBuilder builder = new StringBuilder();
        int i = 0;
        while (matcher.find()) {
            Object replacement = replacementMap.opt(matcher.group(2));
            builder.append(str.substring(i, matcher.start() == 0 ? 0
                    : matcher.start() + 1));
            builder.append(replacement != null ? replacement : "");
            i = matcher.end();
        }
        builder.append(str.substring(i, str.length()));

        String result = builder.toString();
        result = result.replace("\\{", "{");
        result = result.replace("\\}", "}");

        return result;
    }

    /**
     * String helper to ensure the object safely translates to a string, will not return null
     */
    public static String toString(Object o) {
        return o != null ? o.toString() : "";
    }
}

Related

  1. replace(String from, String to, String source)
  2. replace(String line, String oldString, String newString)
  3. replace(String originalString, String searchString, String replaceString)
  4. replace(final String text, final String fromText, final String toText)
  5. replaceAll(String input, String searchStr, String replaceWithStr)
  6. replaceAllKanaWith(String text, String replacement)
  7. replaceAllKanjiWith(String text, String replacement)