Is this a good solution for this regex exercise?
The problem is that I have to extract the email addresses from the provided text. This is my final code:
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, fo开发者_如何转开发o@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);
Through using this regular expression I eliminate email addresses like: hi@.email.com, hi@email.com., hi@e..mail.com and so on... Is there a better way of doing so?
Maybe something like that :
[\w\.]+@[\w\.]+[\w\.]*\.\w{2,4}
- [\w\.]+ : First part at least one time with or without 'dot'
- @ : mandatory for email
- [\w\.]+ : first part of domain name (myhost)
- [\w\.]* : optional part of domain name (my.host)
- \. : mandatory 'dot'
- \w{2,4} : last part of host (.fr, .info, .tel)
精彩评论