解析文本中的邮件地址和url

(1)、使用场景

从给定的文件中解析出所需要的文本是从事文本处理时常见的一项任务。诸如电子邮件地址、URL等都能够借助适合的正则表达式找出来。我们通常需要从一个包含大量无关字符及单词的电子邮件客户列表或HTML网页中将电子邮件地址解析并提取出来。


(2)、正则匹配

匹配一个电子邮件地址的正则表达式如下:

[A-Za-z0-9._]+@[A-Za-z0-9.]+\.[a-zA-Z]{2,4}

匹配HTTP URL的正则表达式如下:

http://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}


(3)、示例

示例1:匹配电子邮件

[root@MuBanJi_01t]# cat a5.txt

this is aline of text contains, #[email protected]. andemail address,

blog"http://www.google.com", [email protected] dfdfdfdddfdf;[email protected]

Heading

[root@MuBanJi_01t]# cat a5.txt |grep -E -o"[A-Za-z0-9._]+@[A-Za-z0-9.]+\.[a-zA-Z]{2,4}"

[email protected]

[email protected]

[email protected]

[root@MuBanJi_01t]#

 

示例2:匹配URL

[root@MuBanJi_01t]# cat a5.txt

this is aline of text contains, #[email protected]. andemail address,

blog"http://www.google.com", [email protected];[email protected]

Heading

[root@MuBanJi_01t]# cat a5.txt |grep -E -o"http://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}"

http://www.google.com

http://code.google.com

[root@MuBanJi_01t]#