REGEX extracting specific part non greedy
<p>I'm new to Python 2.7.  Using regular expressions, I'm trying to extract from a text file just the emails from input lines.  I am using the non-greedy method as the emails are repeated 2 times in the same line.  Here is my code:</p>

<pre><code>import re
f_hand = open('mail.txt')
for line in f_hand:
    line.rstrip()
    if re.findall('\S+@\S+?',line): print re.findall('\S+@\S+?',line)
</code></pre>

<p>however this is what i"m getting instead of just the email address:</p>

<pre><code>['href="mailto:secretary@abc-mediaent.com"&gt;sercetary@a']
</code></pre>

<p>What shall I use in <code>re.findall</code> to get just the email out?  </p>

<p>This is the format of an email address - <a href="https://tools.ietf.org/html/rfc5322#section-3.4.1" rel="nofollow">https://tools.ietf.org/html/rfc5322#section-3.4.1</a>.</p>

<p>Keeping that in mind the regex that you need is - <code>r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)"</code>. <em>(This works without having to depend on the text surrounding an email address.)</em></p>

<p>The following lines of code -</p>

<pre><code>html_str = r'&lt;a href="mailto:sachin.gokhale@indiacast.com"&gt;sachin.gokhale@indiacast.com&lt;/a&gt;'
email_regex = r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)"
print re.findall(email_regex, html_str)
</code></pre>

<p>yields -  </p>

<pre><code>['sachin.gokhale@indiacast.com', 'sachin.gokhale@indiacast.com']
</code></pre>

<p>P.S. - I got the regex for email addresses by googling for "<em>email address regex</em>" and clicking on the first site - <a href="http://emailregex.com/" rel="nofollow">http://emailregex.com/</a></p>

python regex python-2.7 non-greedy