arul selvan
arul selvan

Reputation: 624

regex to extract matching text and any number from email

I want to extract the order number like "SPR 0002745" (starting with "SPR" plus one space and followed by a 7 digit number - with preceding zeros) from an email I receive. I will "star" and mark the email as "important" in Gmail. Then I will run the below function.

I want to extract an amount (a number - maybe with comma , maybe with a decimal) found in the email.

I am not able to use regex. Getting null as output.

  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

Upvotes: 0

Views: 198

Answers (1)

mshcruz
mshcruz

Reputation: 1987

This should match the order number you described: var complaintno = body.match(/SPR \d{7}/) (SPR followed by a space and seven digits). For example:

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
}

Upvotes: 1

Related Questions