Python - Injecting html tags into strings based on regex match
<p>I wrote a script in Python for custom HTML page that finds a word within a string/line and highlights just that word with use of following tags where instance is the word that is searched for.</p>

<pre><code>&lt;b&gt;&lt;font color=\"red\"&gt;"+instance+"&lt;/font&gt;&lt;/b&gt;
</code></pre>

<p>With the following result:
<a href="http://i.stack.imgur.com/t3KpN.png" rel="nofollow"><img src="http://i.stack.imgur.com/t3KpN.png" alt="enter image description here"></a></p>

<p>I need to find a word (case insensitive) let's say "port" within a string that can be port, Port, SUPPORT, Support, support etc, which is easy enough.</p>

<pre><code>pattern = re.compile(word, re.IGNORECASE)
find_all_instances = pattern.findall(string_to_search)
</code></pre>

<p>However my strings often contain 2 or more instances in single line, and I need to append 
<code>&lt;b&gt;&lt;font color=\"red\"&gt;"+instance+"&lt;/font&gt;&lt;/b&gt;</code> to each of those instances, without changing cases.</p>

<p>Problem with my approach, is that I am attempting to itterate over each of instances found with findall (exact match), 
while multiple same matches can also be found within the string.</p>

<pre><code>for instance in find_all_instances:
    second_pattern = re.compile(instance)
    string_to_search = second_pattern.sub("&lt;b&gt;&lt;font color=\"red\"&gt;"+instance+"&lt;/font&gt;&lt;/b&gt;", string_to_search)
</code></pre>

<p>This results in following:</p>

<pre><code>&lt;b&gt;&lt;font color="red"&gt;&lt;b&gt;&lt;font color="red"&gt;&lt;b&gt;&lt;font color="red"&gt;Http&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;&lt;/b&gt;&lt;/font&gt;
</code></pre>

<p>when I need </p>

<pre><code>&lt;b&gt;&lt;font color="red"&gt;Http&lt;/font&gt;&lt;/b&gt;
</code></pre>

<p>I was thinking, I would be able to avoid this if I was able to find out exact part of the string that the pattern.sub substitutes at the moment of doing it, 
however I was not able to find any examples of that kind of usage, which leads me to believe that I am doing something very wrong.</p>

<p>If anyone have a way I could use to insert <code>&lt;b&gt;&lt;font color="red"&gt;instance&lt;/font&gt;&lt;/b&gt;</code> without replacing <code>instance</code> for all matches(case insensitive), then I would be grateful.</p>

<p>Maybe I'm misinterpretting your question, but wouldn't re.sub be the best option?</p>

<p>Example: <a href="https://repl.it/DExs" rel="nofollow">https://repl.it/DExs</a></p>

python html regex string tags