title: How to replace a list of strings in a text where some of them are substrings of other?
body: <p>I have a text containing some words that I would like to tag, and the words to be tagged are contained in a List. The problem is that some of those words are substrings of others, but I want to tag the longest recognized string from the list.</p>
  
  <p>For example, if my text is "foo and bar are different from foo bar." and my list contains "foo", "bar" and "foo bar" the result should be "[tag]foo[/tag] and [tag]bar[/tag] are different from [tag]foo bar[/tag]."</p>
  
  <pre><code>String text = "foo and bar are different from foo bar.";
  
  List&lt;String&gt; words = new ArrayList();
  words.add("foo");
  words.add("bar");
  words.add("foo bar");
  
  String tagged = someFunction(text, words);
  </code></pre>
  
  <p>What should be the code of someFunction in such a way that the value of the string taggedText is <code>&lt;tag&gt;foo&lt;/tag&gt; and &lt;tag&gt;bar&lt;/tag&gt; are different from &lt;tag&gt;foo bar&lt;/tag&gt;.</code> ?</p>