如何使用 Google Apps 脚本针对每个键值从 Gmail 正文中提取值?

How to Extract Values from Gmail Body using Google Apps Script against Each Key Value?

我经常收到银行发来的关于不同基金买卖利率的电子邮件,我想从电子邮件正文中提取基金价值并将其每天粘贴到我的 google 表格中进行分析他们的起伏。

到目前为止,我所取得的成就是将电子邮件正文提取为纯文本,并尝试使用表扬和正则表达式,但未能仅实现值。

下面是我的代码。

function NBPFundUpdate(){
  
  // SKIP TO OUT OF OFFICE HOURS AND DAYS
    var nowH=new Date().getHours();
    var nowD=new Date().getDay();
    //Logger.log(nowD);
    //Logger.log('day : '+nowD+'   Hours : '+nowH)
    if (nowH>19||nowH<8||nowD==0) { return }
    //if (nowH>17||nowH<8||nowD==6||nowD==0) { return }

  var sourceSpreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = sourceSpreadsheet.getActiveSheet();
  
    // START OPERATION
  var Gmail = GmailApp;
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var MasterSheet = ss.getSheetByName("Master");
  var index = 2;
  var aa = 0;
  var na = 0;

  // SEARCH EMAIL
  var query = 'from: no-reply@nbpfunds.net, subject: NBP FUNDS NAV';
  var threadsNew = Gmail.search(query);
  Logger.log(threadsNew.length);

  //check if thread found or not
  if (threadsNew.length ==0) { return }

  var lastscantime = threadsNew[0].getLastMessageDate();
  var master = ss.getSheetByName("Master");
  master.getRange("Z1").setValue(lastscantime);
  Logger.log(lastscantime);

  //loop all emails
  for(var n in threadsNew){
    var thdNew  = threadsNew[n]; 
    var msgsNew = thdNew.getMessages(); 
    var msgNew = msgsNew[msgsNew.length-1];
  // GET ATTACHMENT
    var bodyNew = msgNew.getBody();
    var plainbody  = msgNew.getPlainBody();
    var subject = msgNew.getSubject();
    var Etime = msgNew.getDate();

    Logger.log(Etime);
    Logger.log(subject);
    Logger.log(plainbody);
    
    var NGSLFbuying = /NBP GOVERNMENT SECURITIES LIQUID FUND\n(.*?)$/gm.exec(plainbody);
    Logger.log(NGSLFbuying);

    var NGSLFSelling = /NBP GOVERNMENT SECURITIES LIQUID FUND\n(.*?)$/gm.exec(plainbody);
    Logger.log(NGSLFSelling);
    
  }
}

Logger.log(plainbody)的结果;在下面。

Logger.log(NGSLFbuying)的结果;为空见下图截图

供您参考,我希望最终结果在我的 google 电子表格中看起来像这样;

如果有小伙伴帮助我实现这个,我将非常感谢他/她。

您正在使用 \n 但价格前没有换行符。

const plainbody = `something before
NBP GOVERNMENT SECURITIES LIQUID FUND 1 2
something after`;

const [line, buy, sell] = /NBP GOVERNMENT SECURITIES LIQUID FUND (.*?) (.*?)$/gm.exec(plainbody);
console.log(line);
console.log(buy);
console.log(sell);