首页 > 解决方案 > 正则表达式从电子邮件中提取匹配的文本和任何数字

问题描述

我想从收到的电子邮件中提取像“SPR 0002745”这样的订单号(以“SPR”开头加一个空格,后跟一个 7 位数字 - 前面有零)。我将在 Gmail 中“加星标”并将电子邮件标记为“重要”。然后我将运行以下函数。

我想提取在电子邮件中找到的金额(一个数字 - 可能带有逗号,可能带有小数)。

我无法使用正则表达式。获取 null 作为输出。

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var filter = "label:inbox has:nouserlabels is:important in:Starred"; 
  var threads = GmailApp.search(filter);  
  if (threads.length == 0) {
    ss.toast("No message without label, marked star and important", "Remove label, mark star and important first", -1); 
    return;
  }
  for (var i = 0; i < threads.length; i++) { // Loop through the threads
    var thisThread = threads[i]; // Get a speific thread
    var messages = thisThread.getMessages(); // Get the messages in that thread
    var messageCount = thisThread.getMessageCount(); // Count the number of messages in that thread
    var lastMessage = messages[messageCount - 1]; // Get the last message in that thread. The first message is numbered 0.
    break;
  }
  var message = lastMessage;
  var body = message.getPlainBody();//body field
  Logger.log(body);//working 
  var complaintno = body.match(/^SPR\ (.*)$/)
  Logger.log(complaintno); //returnig null
  var amount1 = body.match(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:(\.|,)\d+)?$/); 
  var amount2 = body.match(/^([0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?|\.[0-9]+)$/);
  Logger.log(amount1);//returnig null
  Logger.log(amount2);//returnig null

标签: google-apps-scriptgoogle-sheets

解决方案


这应该与您描述的订单号匹配var complaintno = body.match(/SPR \d{7}/):(SPR后跟一个空格和七位数字)。例如:

function testRegex() {
  const body = 'Exercitationem commodi enim hic sunt maiores. Aperiam sunt praesentium fugit rem nemo et accusantium. Aut ab est sit mollitia eaque. Aliquam hic vel ut tempore quo quia enim nostrum. Quia aut qui ex voluptatibus: SPR 0002745 Ullam vel asperiores ut suscipit repellat. Velit porro qui et sunt et ea doloremque. Ipsum modi in dolores rerum.';
  const complaintNumber = body.match(/SPR \d{7}/)[0];
  Logger.log(complaintNumber); // This outputs SPR 0002745
}

推荐阅读