You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script正则提取优化:去除星号与邮件冗余内容

解决方案

要实现去除首尾星号、提取纯净邮箱地址的需求,需要针对性调整正则表达式,并增加容错处理,以下是具体修改方案:

修改后的完整代码

function extractDetails(message){
      
  var emailData = {
    date: "Null",
    fullName: "Null",
    emailAddr: "Null",
    phoneNum: "Null",
  }
  var emailKeywords = {
    fullName: "First Name:",
    emailAddr: "Email:",
    phoneNum: "Phone Number:",
  }
  
  emailData.date = message.getDate();
  emailData.body = message.getPlainBody();
  
  var regExp;
  
  // 提取姓名:捕获*包裹的内容,自动去除首尾星号
  regExp = new RegExp("(?<=" + emailKeywords.fullName + " *)\\*(.*?)\\*");
  const nameMatch = emailData.body.match(regExp);
  emailData.fullName = nameMatch ? nameMatch[1].trim() : "Null";
  
  // 提取电话:捕获*包裹的内容,自动去除首尾星号
  regExp = new RegExp("(?<=" + emailKeywords.phoneNum + " *)\\*(.*?)\\*");
  const phoneMatch = emailData.body.match(regExp);
  emailData.phoneNum = phoneMatch ? phoneMatch[1].trim() : "Null";
  
  // 提取邮箱:先捕获*包裹的内容,再从中提取纯净地址
  regExp = new RegExp("(?<=" + emailKeywords.emailAddr + " *)\\*(.*?)\\*");
  const emailMatch = emailData.body.match(regExp);
  if (emailMatch) {
    // 用邮箱专用正则提取纯净地址,剔除冗余的<xxx@xxx.com>内容
    const pureEmailReg = /([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/;
    const pureEmailMatch = emailMatch[1].match(pureEmailReg);
    emailData.emailAddr = pureEmailMatch ? pureEmailMatch[0].trim() : "Null";
  } else {
    emailData.emailAddr = "Null";
  }

  return emailData; // 返回处理后的数据,方便同步到Google Sheets
}

关键修改说明

  • 姓名/电话提取优化:
    正则(?<=关键词 *)\*(.*?)\*的作用:
    • (?<=关键词 *):匹配关键词后的任意空格,避免空格干扰
    • \*(.*?)\*:非贪婪捕获*之间的真实内容,通过match[1]直接获取去除星号后的值
  • 邮箱提取优化:
    分两步处理:先捕获*包裹的全部内容,再用专业邮箱正则提取核心地址,自动过滤冗余的<abc@gmail.com>格式内容
  • 容错处理:
    增加匹配结果判断,避免邮件格式异常时脚本报错,保证运行稳定性

内容的提问来源于stack exchange,提问作者Samy Abdullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:01:12