Java Map Replace replaceVars(String origString, Map vars)

Here you can find the source of replaceVars(String origString, Map vars)

Description

Performs variable substitution for a string.

License

Apache License

Parameter

Parameter Description
origString unmodified string
vars Hashtable of replacement values

Return

modified string

Declaration

public static String replaceVars(String origString, Map vars) 

Method Source Code

//package com.java2s;
/*/*www.  j ava 2 s . c  o m*/
 * Copyright 2000-2001,2004 The Apache Software Foundation.
 * 
 * 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.Map;

public class Main {
    /**
     * Performs variable substitution for a string. String is scanned for ${variable_name} and if one is found,
     * it is replaced with corresponding value from the vars hashtable.
     * 
     * @param origString unmodified string
     * @param vars Hashtable of replacement values
     * @return modified string
     * @exception Exception
     */
    public static String replaceVars(String origString, Map vars) {

        StringBuffer finalString = new StringBuffer();
        int index = 0;
        int i = 0;
        String key = null;
        String value = null;
        while ((index = origString.indexOf("${", i)) > -1) {
            key = origString.substring(index + 2, origString.indexOf("}", index + 3));
            value = (String) vars.get(key);
            finalString.append(origString.substring(i, index));
            if (value != null) {
                finalString.append(value);
            } else {
                finalString.append("${" + key + "}");
            }
            i = index + 3 + key.length();
        }
        finalString.append(origString.substring(i));

        return finalString.toString();
    }
}

Related

  1. replaceToStringBuilder(String s, String begin, String end, Map values)
  2. replaceValues(String s, String begin, String end, Map values)
  3. replaceValuesToSynonyms(Map dic, Map synonims)
  4. replaceVariable(final String src, final Map value)
  5. replaceVariables(String chart, Map variables)
  6. replaceVars(String s, Map m)
  7. stringReplace(Map map, String line)
  8. unescape(String cooked, char escapeChar, Map replacements)
  9. zipToMap(String[] searchStrings, String[] replacements)