Extract specific string part from HTML content with Regex
<p>I'm trying to extract with REGEX from the following string:</p>

<p><code>&lt;tr class="data"&gt;&lt;td class="first"&gt;&lt;a href="en/clinics/al-khayal-medical-centre-6d15db1f.aspx"&gt;AL KHAYAL MEDICAL CENTRE&lt;/a&gt;&lt;/td&gt;&lt;td class="second not-responsive"&gt;&lt;a href="/portal/en/healthcare/clinics.aspx?speciality=Urology"&gt;Urology&lt;/a&gt;&lt;/td&gt;&lt;td class="third"&gt;&lt;label style="display:block ;direction:ltr; text-align:left"&gt;042765600&lt;/label&gt;&lt;/td&gt;&lt;td class="fourth"&gt;&lt;a href="http://www.alkhayalmedicalcentre.com" target="_blank"&gt;www.alkhayalmedicalcentre.com&lt;/a&gt;&lt;/td&gt;&lt;td class="fifth not-responsive"&gt;&lt;a class="clinic-details btn noborder basic small" href="en/clinics/al-khayal-medical-centre-6d15db1f.aspx" rel="1dfd7cf2-49c8-43eb-80b8-9393c9f48ca4"&gt;More Info&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;</code></p>

<p>I'm trying to extract just the following part: </p>

<pre><code>en/clinics/almavita-medical-clinic-fz-llc.aspx    
</code></pre>

<p>The modern way of doing this is to use something like BeautifulSoup. One does not try to process mark up using regular expressions anymore because the resulting code is unreadble and even the slightest change to the markup can break your beautifully crafted regular expression.</p>

<pre><code>from bs4 import BeautifulSoup

bs = BeautifulSoup('&lt;tr class="data"&gt;&lt;td class="first"&gt;&lt;a href="en/clinics/al-khayal-medical-centre-6d15db1f.aspx"&gt;AL KHAYAL MEDICAL CENTRE&lt;/a&gt;&lt;/td&gt;&lt;td class="second not-responsive"&gt;&lt;a href="/portal/en/healthcare/clinics.aspx?speciality=Urology"&gt;Urology&lt;/a&gt;&lt;/td&gt;&lt;td class="third"&gt;&lt;label style="display:block ;direction:ltr; text-align:left"&gt;042765600&lt;/label&gt;&lt;/td&gt;&lt;td class="fourth"&gt;&lt;a href="http://www.alkhayalmedicalcentre.com" target="_blank"&gt;www.alkhayalmedicalcentre.com&lt;/a&gt;&lt;/td&gt;&lt;td class="fifth not-responsive"&gt;&lt;a class="clinic-details btn noborder basic small" href="en/clinics/al-khayal-medical-centre-6d15db1f.aspx" rel="1dfd7cf2-49c8-43eb-80b8-9393c9f48ca4"&gt;More Info&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;   ')

for a in bs.find_all('a'):
   print a['href']
</code></pre>

<p>gives</p>

<pre><code>en/clinics/al-khayal-medical-centre-6d15db1f.aspx
en/clinics/al-khayal-medical-centre-6d15db1f.aspx
/portal/en/healthcare/clinics.aspx?speciality=Urology
http://www.alkhayalmedicalcentre.com
en/clinics/al-khayal-medical-centre-6d15db1f.aspx
</code></pre>

<p>painless</p>

<p>Update: Original version of this answer, I didn't notice that multiple <code>a</code> tags were available. MOdified to process all <code>a</code> tags. If you want just the first one use bs.a['href']</p>

python regex python-2.7 html-parsing