Google Apps Script Regex exec () returns null

When I run the code below in debug mode, I get the expected value at the first iteration of the for loop, but zero at the second, as shown in the images:

First iteration: enter image description here

Second iteration: enter image description here

What am I doing wrong?

The code I use is:

var newer_than = ' newer_than:2d'; //added for faster debugging var subjectIdentifier = '"Ingress Portal Submitted: "'; var searchString = 'subject:'+subjectIdentifier+newer_than; function getPortalName(string) { var myRegexp = /: (.+)/g; var match = myRegexp.exec(string); var portalName = match[1]; return portalName; } function getPortalsSubmitted() { var threads = GmailApp.search(searchString); for (i=0; i<threads.length; i++) { var subject = threads[i].getFirstMessageSubject(); var portalName = getPortalName(subject); var subDate = threads[i].getMessages()[0].getDate(); Logger.log([portalName,subDate]); } } function updatePortals() { var threads = GmailApp.search('subject:"Ingress Portal"'); for (i=0; i<threads.length; i++) { Logger.log(threads[i].getFirstMessageSubject()); } } 
+4
source share
1 answer

Although this question has already been answered by comments, I will make the correct answer.

An important issue for understanding this problem is exec behavior when the regular expression has the g flag. Which, when called, will sequentially try to search for the "next" match, even if you pass another line. Here is the documentation link on MDN.

And although MDN states that you should take care not to recreate the RegExp object (even the literal), because it could reset the lastIndex . At least in Script applications this is not so. If the regex literal is used in the same place over and over again, Script applications cache the regex and reuse the same object.

These two combined effects meant that you unexpectedly triggered this โ€œnext matchโ€ behavior on your code.

The simplest solution for you is to simply omit the g flag, since you do not need it (you get only the first result). But you could also fix this by replacing the string var myRegexp = /: (.+)/g; on var myRegexp = new RegExp(': (.+)','g'); by forcing Apps Script to give you a new object.

I think the good lesson we can learn from this is this: don't use a flag if you don't need one. Sometimes we are lazy and set flags, without hesitation, "just in case".

+8
source

Source: https://habr.com/ru/post/1484821/


All Articles