-3

i'm having troubles to try to form a regex to make a match from a string to get the email only, the string would be like this: 'Hello we have sent an email to ***foo@hotmail.com check it"

I would like a match that only returns ***foor@hotmail.com and i have tried this with a being the string:

a.match(/\b(?=\w*[@*.])\w+\b/g)
//expected ***foor@hotmail.com

But this only return [foo][hotmail] not even the .com.

Can you help me?

Thank you in advance!

carloscgc
  • 9
  • 4
  • https://stackoverflow.com/questions/42407785/regex-extract-email-from-strings – epascarello Feb 01 '19 at 13:16
  • You get foo and hotmail because you are only asserting the existence of a dot and `@`using the positive lookahead `(?=` but the matching part only uses `\w` which does not match a dot or `@` – The fourth bird Feb 01 '19 at 13:27

1 Answers1

-1

You can try using a regexpr like ^.+ (.+@.+) .*$. In the JS console ow a browser you can test it:

EDITED

const text = "Hello we have sent an email to ***foo@hotmail.com check it"
const result = text.match(/^.+ (.+@[^ ]+) .*$/)
// returns ["Hello we have sent an email to ***foo@hotmail.com check it", 
"***foo@hotmail.com", index: 0, input: "Hello we have sent an email to ***foo@hotmail.com check it", groups: undefined]

As you can see, result[1] contains the desired mail address "***foo@hotmail.com".

You can test it with https://regex101.com, too.

Pietro Martinelli
  • 1,695
  • 12
  • 15
  • Can I know the reason of downvoting my answer? – Pietro Martinelli Feb 01 '19 at 13:42
  • But it *doesn't* contain the desired address. It's not only the address, that is - you show yourself the result is `"***foo@hotmail.com check"` which is more than the email itself. – VLAZ Feb 01 '19 at 14:09
  • May be I don't understand the question: what is the desider output you should obtain? The question states `//expected ***foor@hotmail.com`, so, I've thinked to a regexpr matching the full email address... – Pietro Martinelli Feb 01 '19 at 14:33
  • The example you've given matches and returns `"***foo@hotmail.com check"` as output. You even say so yourself "*As you can see, `result[1]` contains the desired mail address "***foo@hotmail.com check*" - the output required is *just* the email, so `" check"` should not be there. – VLAZ Feb 01 '19 at 14:51
  • Uuuuuh! Copy&Paste error... I copied a previous version of the regexpr from my editor :-( ... thank you for catching it! I edit my answer providing the correct regexpr... – Pietro Martinelli Feb 01 '19 at 15:23
  • I edited my original answer fixing the problem you noticed... I hope you can appreciate mi answer now! – Pietro Martinelli Feb 02 '19 at 12:46