I received a request to write some regex to find an email address after a specific phrase (Buyer's email address:). But, the request didn't specify that the email COULD possibly be on a newline or have multiple spaces between. Not being proficient at regex I'm here to throw myself at the feet of the regex gods. Here's what I had originally written that worked when there was just a space after the phrase followed by the email address:

    Pattern myPattern = Pattern.compile('Buyer\'s email address: ([\\w\\d.\\_\\%\\+\\-]+@[\\w\\d\\.\\-]+\\.[\\w]{2,4})');
    Matcher myMatcher = myPattern.matcher(emailBody);
    while(myMatcher.find()) {
        emailFrom = myMatcher.group(1).trim();

Is there a way that I can find the first instance of an email address after the phrase "Buyer's email address:" regardless of spaces, or line-breaks, or carriage returns, or, well, anything else?


2 Answers 2


Personally, I wouldn't try and solve it all in one Regex. Maybe you could, but email regex validation will be problematic.

Instead, try breaking the problem down into more manageable chunks.

The Buyer's email address: prefix seems like a solid starting point for an indexOf() call. Then narrow your search to immediately after that index (and the length of the prefix). Starting from the new index, you could easily clean out any white space characters with a trim(). Now the email address, if present, would be the first thing at the start of the trimmed string.

  • Thanks for the idea! I'll include my complete method for anyone who needs it in a new comment.
    – Wilock
    Jun 16, 2016 at 14:37

Here is the complete method after I used Daniel Ballinger's suggestion above.

NOTE: In my scenario it is acceptable to return a blank string if no email address was found in the email's body text.

public String getFromEmailInEmailBody(String emailBody) {
            string emailFrom = '';        
            Pattern myPattern1 = Pattern.compile('Buyer\'s email address:');
            Matcher myMatcher1 = myPattern1.matcher(emailBody);
            while(myMatcher1.find()) {
                string phrase1 = myMatcher1.group(0).trim();
                integer phrase1Len = phrase1.length()+1;
                string substring = emailBody.mid(emailBody.indexOf(phrase1)+phrase1Len, emailBody.length()).trim();
                Pattern myPattern2 = Pattern.compile('([\\w\\d.\\_\\%\\+\\-]+@[\\w\\d\\.\\-]+\\.[\\w]{2,4})');
                Matcher myMatcher2 = myPattern2.matcher(substring);
                    emailFrom = myMatcher2.group(0).trim();
            return emailFrom;       

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .