メモ Java正規表現 ${key1}→val1

private String replaceValue(String value, Properties prop){
    Pattern pattern = Pattern.compile("\\$\\{.+?\\}");
    Matcher matcher = pattern.matcher(value);
    StringBuffer sb = new StringBuffer();

    while (matcher.find()) {
        String group = matcher.group();
        String repKey = group.substring(2, group.length()-1);
        if(prop.containsKey(repKey)){
            String repValue = prop.getProperty(repKey);
            matcher.appendReplacement(sb, repValue);
        }
    }
    matcher.appendTail(sb);
    return sb.toString();
}

public static void main(String[] args) {
    Properties prop = new Properties();
    prop.setProperty("key1","val1");
    prop.setProperty("key2","val2");
    String result = new MyClass().replaceValue("bbb${key1}bbb${key2}", prop);
    System.out.println(result);
}

結果

bbbval1bbbval2