Java Regex String Replace replace_values(HashMap values, String str)

Here you can find the source of replace_values(HashMap values, String str)

Description

replacvalues

License

Open Source License

Declaration

public static String replace_values(HashMap<String, String> values,
            String str) 

Method Source Code

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

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static String replace_values(HashMap<String, String> values,
            String str) {//ww  w . j  a v a2 s. com
        //Create large String from String set with spacer "|"
        StringBuilder sbStr = new StringBuilder();
        int i = 0;
        for (String s : values.keySet()) {
            i++;
            sbStr.append(s);
            if (i < values.size()) {
                sbStr.append("|");
            }
        }

        String patternString = "%(" + sbStr.toString() + ")%";
        Pattern pattern = Pattern.compile(patternString);

        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, values.get(matcher.group(1)));
        }

        matcher.appendTail(sb);

        return sb.toString();
    }
}

Related

  1. replace(String text, String findPattern, String replacePattern)
  2. replace(String text, String targetText, String newText)
  3. replace(String text, String[] searchStrings, String[] replacements)
  4. replace(String val)
  5. replace(String value)
  6. replace_with_in(String aStringToReplace, String aNewString, String aString)