title: Java Regex: Replace all ${placeholders} with map values
body: <p>I'm trying to replace all occurrences of ${placeholders} with values from a lookup map of placeholder -&gt; value</p>
  <p>The code below doesn't quite cut it.</p>
  <pre><code>Expected :[foobar, foobar, foobar, afoobbarc]
  Actual   :[foobar, foobar, ${key1}bar, a${key1}bbarc]
  </code></pre>
  <p>Can anyone think of a better regex?</p>
  <pre><code>private static final Pattern replaceRegex = Pattern.compile(&quot;.*(\\$\\{?([^}]+)}).*&quot;);
  public static String resolvePlaceholder(Map&lt;String, String&gt; map, String s){
    String returnValue = s;
    for (Matcher m = replaceRegex.matcher(s); m.find(); ) {
      if (map.containsKey(m.group(2))) {
        returnValue = returnValue.replace(m.group(1), map.get(m.group(2)));
      }
    }
    return returnValue;
  }
  
  @Test
  public void test() {
    // Given a map of a million entries
    Map&lt;String, String&gt; veryBigMap = new HashMap&lt;&gt;();
    veryBigMap.put(&quot;key1&quot;, &quot;foo&quot;);
    veryBigMap.put(&quot;key2&quot;, &quot;bar&quot;);
    // And test cases
    Stream&lt;String&gt; testCases = Stream.of(&quot;${key1}bar&quot;, &quot;foo${key2}&quot;, &quot;${key1}${key2}&quot;, &quot;a${key1}b${key2}c&quot;);
  
    // When resolving placeholders
    List&lt;String&gt; actual = testCases
        .map(t -&gt; resolvePlaceholder(veryBigMap, t))
        .collect(Collectors.toList());
  
    // Then placeholders get replaced
    assertEquals(
        Arrays.asList(&quot;foobar&quot;, &quot;foobar&quot;, &quot;foobar&quot;, &quot;afoobbarc&quot;),
        actual);
  }
  </code></pre>
  <p>Many thanks</p>
  <p>Fil</p>