简体   繁体   中英

Parsing string to find email within string via Google Apps Script

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 john.doe@aol.com 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.

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;
}

An email address parsing library "email-addresses" has been adapted for Google Apps Script. Source is forked and available as a gist .

  • Publicly available, library key M26NvEFUvGLQadhq7G3OQmgFzUAA6_aCl.
  • Documentation available here .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM