Reputation: 317
I'm not a new coder, but new to google app scripts. I am trying to take a string and find the email address contained within the string.
string = "This is the body of the cell where I will be looking. This body has an email in it somewhere like [email protected] here.";
email = FindEmail(string);
MailApp.sendEmail(email, "Completion Email", "", "this is the email message");
I need to build a function called FindEmail but frankly have no idea how to start.
Upvotes: 1
Views: 3556
Reputation: 45710
An email address parsing library "email-addresses" has been adapted for Google Apps Script. Source is forked and available as a gist.
However... it will not find the email address in the string example you give! It expects the string containing addresses to loosely conform to RFC 5322.
Upvotes: 1
Reputation: 45710
While there are numerous solutions to this on SO already, the ones I've found need tweaking to provide the simplicity you're looking for.
Here's a simple function condensed from all those other answers - the regular expression is a bit of overkill, actually, but can also be used to validate in many cases. It returns an array of addresses, so if you only want the first one, you would code email = findEmails(string)[0]
... but really, you should do some error checking before trusting that.
/**
* Return an array of all email addresses found in input string.
*/
function FindEmails(input) {
var regex = /(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/gm
var result = input.match(regex);
return result;
}
Upvotes: 4