1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.tradefed.util; 18 19 import java.util.Map; 20 import java.util.regex.Matcher; 21 import java.util.regex.Pattern; 22 23 /** Utility class for escaping strings for common string manipulation. */ 24 public class StringUtil { 25 26 /** 27 * Expand all variables in a given string with their values in the map. 28 * 29 * <pre>{@code 30 * Map<String, String> valueMap = new HashMap<>() { 31 * put("FOO", "trade"); 32 * put("BAR", "federation"); 33 * }; 34 * String str = StringUtil.expand("${FOO}.${BAR}", valueMap); 35 * assert str.equals("trade.federation"); 36 * }</pre> 37 * 38 * @param str the source {@link String} to expand 39 * @return the map with the variable names and values 40 */ expand(String str, Map<String, String> valueMap)41 public static String expand(String str, Map<String, String> valueMap) { 42 final StringBuffer sb = new StringBuffer(); 43 final Pattern p = Pattern.compile("\\$\\{([^\\{\\}]+)\\}"); 44 final Matcher m = p.matcher(str); 45 while (m.find()) { 46 final String key = m.group(1); 47 final String value = valueMap.getOrDefault(key, ""); 48 m.appendReplacement(sb, Matcher.quoteReplacement(value)); 49 } 50 m.appendTail(sb); 51 return sb.toString(); 52 } 53 } 54