2

I'm trying to locate/modify text in my Google Document where the text has been broken across a full line break. My regular expression below works when I manually find text in the Google document (CTRL+F) and then search via the regular expression dialog. What is baffling is why the exact same regex doesn't work in the code below on full line breaks, i.e. "\n" (note: the soft line "\v" breaks are ok).

The second approach finds the text but I'm unable to do anything with it as I need the element object in-order to manipulate the text.

  //Test document 1Q6v8ipqA81LoPtpk71NdqTaIEqMjki1KIJbrm0bILBg contains the following text:
  //
  //This Agreement shall not be assigned by either party without the prior\n
  //written consent of the parties hereto

  var doc = DocumentApp.openById('1Q6v8ipqA81LoPtpk71NdqTaIEqMjki1KIJbrm0bILBg');          

  //Method 1 - does NOT locate the text
  var body = doc.getBody(); 
  var pattern = "prior[\s]*written";  
  var foundElement = body.findText(pattern);    
  while (foundElement != null) {
    var foundText = foundElement.getElement().asText();    
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();

    foundElement = body.findText(pattern, foundElement);      
  }

  //Method 2 - locates the text, but I cannot acquire the element object 
  var body2 = doc.getBody().getText(); 
  var pattern2 = /prior[\s]*written/; 
  while (m=pattern2.exec(body2)) 
  { 
    Logger.log(m[0]);         
  }
}
Rubén
  • 34,714
  • 9
  • 70
  • 166
Paul Brown
  • 223
  • 1
  • 14

1 Answers1

0

If this were ever going to work, you would need the regex to be in s (single line) mode. Per https://developers.google.com/apps-script/reference/document/body#findtextsearchpattern,

A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.

So it looks like they have in fact chosen not to support multi-line matches in any way.

chaos
  • 122,029
  • 33
  • 303
  • 309