Extract email sub-strings from large document

前端 未结 11 2199
星月不相逢
星月不相逢 2020-11-28 06:54

I have a very large .txt file with hundreds of thousands of email addresses scattered throughout. They all take the format:

......
         


        
11条回答
  •  渐次进展
    2020-11-28 07:24

    This code extracts the email addresses in a string. Use it while reading line by line

    >>> import re
    >>> line = "should we use regex more often? let me know at  321dsasdsa@dasdsa.com.lol"
    >>> match = re.search(r'[\w\.-]+@[\w\.-]+', line)
    >>> match.group(0)
    '321dsasdsa@dasdsa.com.lol'
    

    If you have several email addresses use findall:

    >>> line = "should we use regex more often? let me know at  321dsasdsa@dasdsa.com.lol"
    >>> match = re.findall(r'[\w\.-]+@[\w\.-]+', line)
    >>> match
    ['321dsasdsa@dasdsa.com.lol', 'dadaads@dsdds.com']
    

    The regex above probably finds the most common non-fake email address. If you want to be completely aligned with the RFC 5322 you should check which email addresses follow the specification. Check this out to avoid any bugs in finding email addresses correctly.


    Edit: as suggested in a comment by @kostek: In the string Contact us at support@example.com. my regex returns support@example.com. (with dot at the end). To avoid this, use [\w\.,]+@[\w\.,]+\.\w+)

    Edit II: another wonderful improvement was mentioned in the comments: [\w\.-]+@[\w\.-]+\.\w+which will capture example@do-main.com as well.

提交回复
热议问题