这是这个正则表达式练习的好方法吗?

时间:2010-12-28 13:03:49

标签: javascript regex email

问题是我必须从提供的文本中提取电子邮件地址。这是我的最终代码:

var a = "A towel, it says, is about the most massively useful thing an interstellar hitchhiker can have. Partly it has great practical value - you can wrap it around you dent@vogon.com for warmth as you bound across the cold moons of Jaglan Beta; you can lie on it on the brilliant marble-sanded beaches of Santraginus V, foo@bar.bar.com inhaling the heady sea vapours; you can sleep under it beneath the stars which shine so redly on the desert world of Kakrafoon; use it john.smith@blah.org to sail a mini raft down the slow heavy river Moth; wet it for use in hand-to- hand-combat; wrap it round your head to ward off glom@flop.net noxious fumes or to avoid the gaze of the Ravenous Bugblatter Beast of Traal (a mindboggingly stupid animal, it assumes that if you can't see it, it can't see you - daft as a bush, but very ravenous); you can wave your towel in emergencies as a distress signal, and of course dry yourself off with it if it still seems to be clean enough.";
var re = /[a-z0-9-_\.]+@[a-z0-9-_]+(?:\.[a-z0-9-_]+)+/gi;
var output = a.match(re);
alert(output);

通过使用这个正则表达式,我删除了以下电子邮件地址:hi @ .email.com,hi @ email.com。,hi @ e..​​mail.com等等...有没有更好的方法?

1 个答案:

答案 0 :(得分:0)

也许是这样的:

[\w\.]+@[\w\.]+[\w\.]*\.\w{2,4}
  • [\ w \。] +:第一部分至少有一部分 时间有无'dot'
  • @:强制要求发送电子邮件
  • [\ w \。] +:域名(myhost)的第一部分
  • [\ w \。] *:域名(my.host)的可选部分
  • \。 :强制性'dot'
  • \ w {2,4}:主持人的最后一部分(.fr,.info,.tel)