title: Parsing strings in Java to replace markers with specific data
body: <p>I have a bunch of strings which contain some specific markers that should be replaced with images. So at first I created hash map with markers and images:</p>
  <pre><code>Map&lt;String, String&gt; images = new HashMap&lt;String, String&gt;();
  images.put(&quot;:img:howdy:&quot;, &quot;path/images/hello.png&quot;);
  images.put(&quot;:img:code:&quot;, &quot;path/images/code.png&quot;);
  images.put(&quot;:img:smile:&quot;, &quot;path/images/sm.png&quot;);
  //...and 70 more records
  </code></pre>
  <p>Strings look like:</p>
  <blockquote>
  <p>This is a string :img:howdy:, you know it :img:smile:</p>
  <p>And even more:img:smile:</p>
  <p>This is a string with images:img:code::img:smile:</p>
  </blockquote>
  <p>After parsing all markers are planned to be replaced with images.</p>
  <p>I stuck at the following point:</p>
  <pre><code>Map&lt;String, String&gt; images = new HashMap&lt;String, String&gt;();
  images.put(&quot;:img:howdy:&quot;, &quot;path/images/hello.png&quot;);
  images.put(&quot;:img:code:&quot;, &quot;path/images/code.png&quot;);
  images.put(&quot;:img:smile:&quot;, &quot;path/images/sm.png&quot;);
  
  String[] strings = {&quot;This is a string :img:howdy:, you know it :img:smile:&quot;,
                   &quot;And even more:img:smile:&quot;,
                   &quot;This is a string with images:img:code::img:smile:&quot;};
  
  for (String text : images.keySet()) {
      for (String string : strings) {
          if(string.contains(text)) {
              string.replace(text, images.get(text));
          }
      }
  }
  </code></pre>
  <p>Firstly, markers are replaced, but there're to much iterations.
  Secondly, if I use, for example, StringBuilder, I have a lot of duplications with some markers replaced and some not.</p>
  <p>I'm not strong with string parsing and corresponding algorithms (at the moment), so don't throw stones at me after viewing approach I chose.</p>
  <p><strong>Added</strong>
  Reworked a little as Dariusz Waver suggested and here is what I've got:</p>
  <pre><code>private final String IMAGE_PATTERN = &quot;:s:\\w+:&quot;;
  
  //.......
  
  Pattern p = Pattern.compile(IMAGE_PATTERN);
  Matcher m = p.matcher(message);
  while(m.find())
  {
      String imgPattern = message.substring(m.start(), m.end());
      String imgPath = ImgPaths.images.get(imgPattern);
      
      //If there's no such image in Images Map
      if(imgPattern != null) {
          message = message.replace(imgPattern, imgPath);
          m.reset(message);
      }
  }
  
  StringBuilder result = new StringBuilder();
  result.append(timestamp).append(&quot; - &quot;).append(sender)
          .append(&quot;: &quot;).append(message);
  </code></pre>
  <p>Is there any way to make it more optmized taking into account that there's a really huge amount of text?</p>