Javascript 对于这个正则表达式练习,这是一个好的解决方案吗?

Javascript 对于这个正则表达式练习,这是一个好的解决方案吗?,javascript,regex,email,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 th

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

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等等有更好的方法吗?

可能是这样的:

[\w\.]+@[\w\.]+[\w\.]*\.\w{2,4}
  • [\w\.]+:第一部分至少一个 带或不带“点”的时间
  • @:电子邮件为必填项
  • [\w\.]+:域名的第一部分(myhost)
  • [\w\.]*:域名的可选部分(my.host)
  • \.:强制性“点”
  • \w{2,4}:主机的最后一部分(.fr、.info、.tel)

    • 可能是这样的:

      [\w\.]+@[\w\.]+[\w\.]*\.\w{2,4}
      
      • [\w\.]+:第一部分至少一个 带或不带“点”的时间
      • @:电子邮件为必填项
      • [\w\.]+:域名的第一部分(myhost)
      • [\w\.]*:域名的可选部分(my.host)
      • \.:强制性“点”
      • \w{2,4}:主机的最后一部分(.fr、.info、.tel)

      • 这是家庭作业吗?另外,我认为谷歌允许电子邮件像“嗨”。@gmail.com,所以你可能需要小心限制。不,我实际上是在高中一年级,所以我年级没有其他人编程。从这里传来:@SB-你对家庭作业有什么兴趣?OP明确表示这是一个“练习”,并对解决问题做出了很好的尝试。我们还能要求什么<代码>:)是.net吗因为正则表达式格式可能会因此而改变。@Pabuc,您将如何使用“基本字符串操作”来完成它?这是家庭作业吗?另外,我认为谷歌允许电子邮件像“嗨”。@gmail.com,所以你可能需要小心限制。不,我实际上是在高中一年级,所以我年级没有其他人编程。从这里传来:@SB-你对家庭作业有什么兴趣?OP明确表示这是一个“练习”,并对解决问题做出了很好的尝试。我们还能要求什么<代码>:)是.net吗因为正则表达式的格式可能会因此而改变。@Pabuc,您如何使用“基本字符串操作”?这允许
        ...a…b…com
        -OP的正则表达式更好一些,尤其是对于域。这允许
        ...a…b…com
        -OP的正则表达式更好一些,尤其是对于域。