Reputation: 970
I asked this question a few days ago:
Unable to get a specific value on a JSON object
The first answer was just perfect. Now I need to modify that regular expression in order to find e-mails. The problem is I don't know anything about regular expressions and I've been looking around but don't seem to be able to pull it off. This is the code:
var m=null
, result=JSON.stringify(response)
, re=/"message":"([^"]+)"/g
, messages=[];
while( m=re.exec(result) ) {
messages.push(m[1]);
Everything is explained on my other question, but basically what this code does is get message":"THIS TEXT"
Now I want to find out whether that text contains an e-mail or not.
I've been checking out many javascript regexp examples and find it rather confusing so if you could give me a little explanation (or something to read) about why it's done the way it's done I'd really appreciate it.
Upvotes: 0
Views: 69
Reputation: 23616
There are some very, very long regexes that you can use to validate emails based on RFC standards. Here is a regex that verifies regexes based on RFC882, which is anything from short and easy-to-understand.
If you wanted to validate anything that looked like an email, you could use this:
^.+@.+\..+$
But, this regex will also allow spaces, and multiple @ symbols. So, you could use this:
^[^@]+@[^@]+\.[^@]+$
But this will allow special characters in the name and TLD, so, here's a short regex that will match almost all English emails (as well as those that aren't english):
^([a-zA-Z0-9\-_\~\!\$\&\'\(\)\*\+\,;\:\=]+)\@(.+)\.([a-zA-Z]{2,36})$
This regex will match the characters a-z
, A-Z
, 0-9
, -
, _
, ~
, !
, $
, &
, '
, (
, )
, *
, +
, ,
, ;
, :
, and =
one or more times before the @
symbol, will match any characters after the @
symbol (almost all characters are now allowed with the new international domains), and allows a-z
or A-Z
2 or more times as the TLD.
There are some international domains that do not have english characters in them, so it may be best to replace [a-zA-Z]{2,36}
with .{2,36}
, if you're expecting and international audience.
Here's a live preview of Regex #1 on regex101.com.
Here's a live preview of Regex #2 on regex101.com.
Here's a live preview of Regex #3 on regex101.com.
Upvotes: 1
Reputation: 362
Regexp you are looking for is long and ugly. The email address definition in RFC standard is too sophisticated and permissive. See "Valid email addresses" section on wikipedia. But, you can check whether string looks like email with this simple regexp:
/^.+@.+\..+$/
The explanation of how this works can be found at Regexper
Upvotes: 2