Warm tip: This article is reproduced from serverfault.com, please click

Regex in textreplace google app script is not working

发布于 2020-11-28 00:22:30

Trying to replace text + date just by date using regex, but it not works:

function myfunction() {  
   var SourceFolder = DriveApp.getFolderById("");
   var Files = SourceFolder.getFiles()
   var body = DocumentApp.getActiveDocument().getBody();
   while(Files.hasNext()) {
       var file = Files.next();
       body.replaceText("Date: \d{2}.\d{2}.\d{4}", "31.10.2020")
   }  
 }

Thanks

Questioner
Alex
Viewed
0
Wiktor Stribiżew 2020-11-28 19:45:21

In your code, var body = DocumentApp.getActiveDocument().getBody(); is declared outside of the loop, so you always refer to the active document body in your while loop.

You may use

while(Files.hasNext()) {
   var file = Files.next();
   var doc = DocumentApp.openById(file.getId()); 
   var body = doc.getBody();
   body.replaceText("Date: \\d{2}\\.\\d{2}\\.\\d{4}", "31.10.2020")
}  

The point here is to use double backslashes in the pattern, and escape the dot chars since otherwise a . matches any char but a line break char.