Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replaceText() RegEx "not followed by"

Any ideas why this simple RegEx doesn't seem to be supported in a Google Docs script?

foo(?!bar)

I'm assuming that Google Apps Script uses the same RegEx as JavaScript. Is this not so?

I'm using the RegEx as such:

DocumentApp.getActiveDocument().getBody().replaceText('foo(?!bar)', 'hello');

This generates the error:

ScriptError: Invalid regular expression pattern foo(?!bar)

like image 820
Terrence Avatar asked Jun 21 '15 19:06

Terrence


1 Answers

As discussed in comments on this question, this is a documented limitation; the replaceText() method doesn't support reverse-lookaheads or any other capture group.

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

Serge suggested a work-around, "it should be possible to manipulate your document at a lower level (extracting text from paragraph etc) but it could rapidly become quite cumbersome."

Here's what that could look like. If you don't mind losing all formatting, this example will apply capture groups, RegExp flags (i for case-insensitivity) and reverse-lookaheads to change:

Little rabbit Foo Foo, running through the foobar.

to:

Little rabbit Fred Fred, running through the foobar.

Code:

function myFunction() {
  var body = DocumentApp.getActiveDocument().getBody();
  var paragraphs = body.getParagraphs();
  for (var i=0; i<paragraphs.length; i++) {
    var text = paragraphs[i].getText();
    paragraphs[i].replaceText(".*", text.replace(/(f)oo(?!bar)/gi, '$1red') );
  }
}
like image 151
Mogsdad Avatar answered Oct 09 '22 06:10

Mogsdad