regex extract email from strings

前端 未结 7 1480
陌清茗
陌清茗 2020-12-01 16:25

I want to know if by using regular expressions I am able to extract emails from the following strings?

The following RE pattern is .*@.*match with all st

7条回答
  •  生来不讨喜
    2020-12-01 17:02

    You can create a function with regex /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/ to extract email ids from long text:

    function extractEmails ( text ){
        return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/gi);
        }
    

    Script in action: Run to see result

    var text = `boleh di kirim ke email saya ekoprasetyo.crb@outlook.com tks... boleh minta kirim ke db.maulana@gmail.com. dee.wien@yahoo.com. . 
    deninainggolan@yahoo.co.id Senior Quantity Surveyor
    Fajar.rohita@hotmail.com, terimakasih bu Cindy Hartanto
    firmansyah1404@gmail.com saya mau dong bu cindy
    fransiscajw@gmail.com 
    Hi Cindy ...pls share the Salary guide to donny_tri_wardono@yahoo.co.id thank a`; 
    
    function extractEmails ( text ){
        return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9_-]+)/gi);
        }
         
        $("#emails").text(extractEmails(text));
    
    

    While the regex in the above code snippet matches most email patterns, but if you still need to match >99% of the email patterns, including the edge cases then use the regex pattern as shown below

    Script in action: Run to see result

    var text = `boleh di kirim ke email saya ekoprasetyo.crb@outlook.com tks... boleh minta kirim ke db.maulana@gmail.com. dee.wien@yahoo.com. . 
    deninainggolan@yahoo.co.id Senior Quantity Surveyor
    Fajar.rohita@hotmail.com, terimakasih bu Cindy Hartanto
    firmansyah1404@gmail.com saya mau dong bu cindy
    fransiscajw@gmail.com 
    Hi Cindy ...pls share the Salary guide to donny_tri_wardono@yahoo.co.id thank a`; 
    
    function extractEmails ( text ){
        return text.match(/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gi);
        }
         
        $("#emails").text(extractEmails(text));
    
    

提交回复
热议问题