user1592380
user1592380

Reputation: 36317

Newline in gmail app script getplainbody function

I'm trying to parse gmail bodies using appscript and the getplainbody() function.

The email body I'm trying to parse looks like:

  *Name:* tom jones
  *Email:* [email protected]
  *Phone Number:* 3021234567, [Hello,

So far I have the following:

function extractEmails() {

// get the spreadsheet
 var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var label = sheet.getRange(1,2).getValue();

// get all email threads that match label from Sheet
var threads = GmailApp.search ("label:" + label);

// get all the messages for the current batch of threads
var messages = GmailApp.getMessagesForThreads (threads);

var emailArray = [];

// get array of email addresses
messages.forEach(function(message) {
message.forEach(function(d) {

  var messagebody = d.getPlainBody()
   var name = messagebody.match(new RegExp('\*Name\:\*' + "(.*)" + ' '));


  emailArray.push(d.getFrom(),d.getTo(),name);
  });
});

I'm getting:

SyntaxError: Invalid quantifier *. (line 56, file "Code")

line 56 is:

 var name = messagebody.match(new RegExp('\*Name\:\*' + "(.*)" + ' '));

What am I doing wrong?

Upvotes: 1

Views: 591

Answers (2)

user6655984
user6655984

Reputation:

You are building a regular expression from a string, which leads to double escaping hell. Strings in JavaScript use backslash for escaping. Thus, executing

str = '\*Name\:\*' + "(.*)" + ' '

results in the string *Name:*(.*) -- notice that backslashes before asterisks are gone; they were treated as escape characters for string building purpose. But you still need them to escape on the level of RegExp object, the second level of hell.

So, either escape backslashes themselves as \\ or (better) use regex literals:

/\*Name:\*(.*) / 

for example

messagebody.match(/\*Name:\*(.*) /)

Upvotes: 2

OblongMedulla
OblongMedulla

Reputation: 1595

Notice if you try this here it will show. http://regexr.com/

\*([A-Z])\w+:\*/g

Upvotes: 1

Related Questions