1

I have a string

Steve Jobs [email protected] somethingElse

I hope to match [email protected] somethingElse (a space in front)

This is my regular expression (JavaScript)

\s.+?@.+

But now it matches Jobs [email protected] somethingElse (a space in front)

I know I can use ? to lazy match the following part, but how to lazy match front part?

3
  • \s\S+@.+? There is no rightmost lazy matching, you'll either have to use a negated character class or a tempered greedy token approach. Commented Jan 16, 2018 at 8:52
  • \s(.+?@.+) extract first captured group. Commented Jan 16, 2018 at 8:57
  • 1
    Use (\S+@\S+)\s*(\S+) and extract first & second captured groups. Commented Jan 16, 2018 at 8:58

3 Answers 3

1

A . can be any character, including the whitespaces.

Normally e-mails don't contain whitespaces. (although it's actually allowed between 2 ")

So you could change the regex so that it looks for non-whitespaces \S before and after the @.
It can be greedy.

A whitespace followed by 1 or more non-whitespaces and a @ and 1 or more non-whitespaces. Then by whitespace(s) and something else:

\s(\S+@\S+)(?:\s+(\S+))?
Sign up to request clarification or add additional context in comments.

2 Comments

I tried Tushar and gurvinder372's too, and they both work. But I feel this one with \S help is a very smart solution!
Well, something like \S+@\S+ is short alright. But it would also capture a string with more than 1 @. Something like [^\s@]+[@][^\s@]+[.]\w+ would be slightly more accurate to capture an e-mail.
1

You can also use trim, split and pop

var output = "Steve Jobs [email protected] ".trim().split(" ").pop();

Regex solution

You can use trim and match

var output = "Steve Jobs [email protected] ".trim().match( /[\w.]+@[\w.]+/g )

Regex - /[\w.]+@[\w.]+$/gi

Edit

var output = "Steve Jobs [email protected] somethingelse ".trim().match( /[\w.]+@[\w.]+/g )

Demo

var  regex = /[\w.]+@[\w.]+/g;

var input1 = "Steve Jobs [email protected] ";
var input2 = "Steve Jobs [email protected] somethingelse ";

var fn = (str) => str.trim().match(regex);

console.log( fn(input1) );
console.log( fn(input2) );

2 Comments

Thanks, I updated my questions a little bit by adding somethingElse, to reveal the more complex real problem. (Sorry, I think I simplified too much at first)
@HongboMiao Please try the regex solution as well.
0

The allowed characters in an email are;

*0-9* | *a-z* | *. - _*

And it must have a @ symbol too.

So our regex must start with allowed characters,

[a-zA-z0-9-_.]

It must continue with @ symbol;

[a-zA-z0-9-_.]+@

Then it can end with .com or anything which includes dot

[a-zA-z0-9-_.]+@[a-zA-z0-9.]+

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.