Regex matches in online tester but not in app script

1,091 views
Skip to first unread message

Harry Hoffman

unread,
Jun 11, 2022, 7:37:50 AM6/11/22
to Google Apps Script Community
Hi Folks,

I'm struggling a bit trying to capture some information via regex in my script. If I try the regex and sample data in regex101.com I get the matches I expect.

I'm capturing the body of each email with:
var text = messages[m].getPlainBody();

and then attempting to match a variety of fields based upon this regex:
var matches = text.match(/From:.*\<(.*)\>\nSent:.*\nTo:.*\<(.*)\>\nSubject:(.*)/m);

The data stored in text is:
________________________________
From: Support <sup...@replacedemail.com>
Sent: Friday, June 10, 2022 6:58:00 AM (UTC-05:00) Eastern Time (US & Canada)
To: Hoffman, Harry <hhof...@anotheremail.com>
Subject: Critical Failed Check: Missing MFA

This email originates from a sender outside of Northeastern University.

[sca logo]
Compliance check failure
Jun 10, 10:58 AM
No MFA Configured

Critical  |  17 failing users since 10 Jun 2022 04:21 GMT 

<TRUNCATED MESSAGE FOR POSTING>

dimud...@gmail.com

unread,
Jun 11, 2022, 9:03:12 AM6/11/22
to Google Apps Script Community
The getPlainBody() function only returns the body text not the headers(which include 'From', 'To', 'Subject' and others). You can get those values using other functions. Check the reference documentation linked below:
https://developers.google.com/apps-script/reference/gmail/gmail-message

Harry Hoffman

unread,
Jun 11, 2022, 10:08:25 AM6/11/22
to Google Apps Script Community
Apologies, I wasn't clear. This is a forwarded message and as such has that information in the body. So if I examine the variable I set called text I see that data  (From, Sent, To, Subject, email body) contained within. I used getPlainBody because that strips all of the HTML formatting and I thought that would make it more straightforward to match what I'm looking for.

Cheers,
Harry



Harry Hoffman

unread,
Jun 11, 2022, 3:13:31 PM6/11/22
to Google Apps Script Community
Ok, figured this out in case it's helpful for anyone else, \n didn't work but \r\n matched correctly. I'm guessing there was a copy/paste difference between the original gmail message and the regex testing website.

Cheers,
harry
Message has been deleted

Colton Robbins

unread,
Jul 14, 2023, 6:52:44 PM7/14/23
to Google Apps Script Community
Harry - Thanks so much for posting your solution! I was having the exact same problem and it was driving me nuts. 
Reply all
Reply to author
Forward
0 new messages