简体   繁体   English

解析字符串以通过Google Apps脚本在字符串中查找电子邮件

[英]Parsing string to find email within string via Google Apps Script

I'm not a new coder, but new to google app scripts. 我不是新编码员,而是Google应用脚本的新手。 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."; string =“这是我要查找的单元格的主体。该主体中有一封电子邮件,例如john.doe@aol.com。”;

email = FindEmail(string); 电子邮件= FindEmail(字符串);

MailApp.sendEmail(email, "Completion Email", "", "this is the email message"); MailApp.sendEmail(电子邮件,“完成电子邮件”,“”,“这是电子邮件”);

I need to build a function called FindEmail but frankly have no idea how to start. 我需要构建一个名为FindEmail的函数,但是坦率地说,不知道如何启动。

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. 尽管在SO上已经有许多解决方案,但我发现需要对其进行调整以提供所需的简单性。

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. 它返回一个地址数组 ,因此,如果只需要第一个地址,则可以将email = findEmails(string)[0]代码编写为email = findEmails(string)[0] ...但是,实际上,您应该在信任它之前进行一些错误检查。

/**
 * 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. 电子邮件地址解析库“电子邮件地址”已针对Google Apps脚本进行了修改。 Source is forked and available as a gist . 源代码是分叉的,可以作为要点使用

  • Publicly available, library key M26NvEFUvGLQadhq7G3OQmgFzUAA6_aCl. 库密钥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. 它期望包含地址的字符串大致符合RFC 5322。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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