title: Python Find & Replace Beautiful Soup
body: <p>I am using Beautiful Soup to replace the occurrences of a pattern with a href link inside a HTML file</p>
  
  <p>I am facing a problem as described below</p>
  
  <pre><code>modified_contents = re.sub("([^http://*/s]APP[a-z]{2}[0-9]{2})", "&lt;a href=\"http://stack.com=\\1\"&gt;\\1&lt;/a&gt;", str(soup))
  </code></pre>
  
  <p>Sample input 1:</p>
  
  <pre><code>Input File contains APPdd34
  
  Output File contains &lt;a href="http://stack.com=APPdd34"&gt; APPdd34&lt;/a&gt;
  </code></pre>
  
  <p>Sample input 2:</p>
  
  <pre><code>Input File contains &lt;a href="http://stack.com=APPdd34"&gt; APPdd34&lt;/a&gt;
  
  Output File contains &lt;a href="http://stack.com=&lt;a href="http://stack.com=APPdd34"&gt; APPdd34&lt;/a&gt;"&gt; &lt;a href="http://stack.com=APPdd34"&gt; APPdd34&lt;/a&gt;&lt;/a&gt;
  </code></pre>
  
  <p>Desired Output File 2 is same as Sample Input File 2.</p>
  
  <p>How can I rectify this problem?</p>