如何用Gmail Google App Script提取邮件纯文本中的首个美元金额
提取Gmail纯文本中的首个美元金额(Google Apps Script)
问题分析
你之前用match/search返回-1,核心原因是正则表达式未正确转义美元符号$(正则里$是字符串结束锚点,必须转义为\$),或者正则没覆盖金额的常见格式(比如整数/带两位小数的金额)。
解决方案
用正确的正则匹配首个美元金额,同时添加容错处理避免数组越界错误。
完整代码示例
// 处理FortisBC邮件 const fortisThreads = GmailApp.search('from:(gas.customerservice@fortisbc.com) AND has:attachment AND newer_than:7d'); if (fortisThreads.length > 0) { const messageFortisBC = fortisThreads[0].getMessages()[0]; const forwardedPlainMessageFortisBC = messageFortisBC.getPlainBody(); // 匹配首个美元金额:支持整数(如$100)或带两位小数(如$246.96) const dollarRegex = /\$(\d+(?:\.\d{2})?)/; const fortisMatch = forwardedPlainMessageFortisBC.match(dollarRegex); const fortisAmount = fortisMatch ? fortisMatch[1] : '未找到金额'; console.log('FortisBC账单金额:', fortisAmount); } else { console.log('未找到符合条件的FortisBC邮件'); } // 处理BC Hydro邮件 const bcHydroThreads = GmailApp.search('from:(notifications@bchydro.com) AND subject:bill AND newer_than:7d'); if (bcHydroThreads.length > 0) { const messageBCHydro = bcHydroThreads[0].getMessages()[0]; const forwardedPlainMessageBCHydro = messageBCHydro.getPlainBody(); const dollarRegex = /\$(\d+(?:\.\d{2})?)/; const bcHydroMatch = forwardedPlainMessageBCHydro.match(dollarRegex); const bcHydroAmount = bcHydroMatch ? bcHydroMatch[1] : '未找到金额'; console.log('BC Hydro账单金额:', bcHydroAmount); } else { console.log('未找到符合条件的BC Hydro邮件'); }
正则表达式说明
\$:转义美元符号,确保匹配文本中的$字符(\d+):匹配一个或多个数字(金额的整数部分)(?:\.\d{2})?:可选的小数部分,?:表示非捕获组(不单独提取这部分),\.\d{2}匹配小数点加两位数字,?表示该部分可省略(兼容整数金额)
关键注意事项
- 必须转义$:直接写
$会被正则当作字符串结束标记,完全匹配不到金额 - 邮件搜索容错:添加
threads.length > 0判断,避免搜索不到邮件时触发数组越界错误 - 匹配结果判断:
match方法返回数组(第一个元素是完整匹配内容,第二个是捕获的金额数字),需先判断是否为null再提取金额
内容的提问来源于stack exchange,提问作者user21081886
相关产品推荐
相关产品推荐

