Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

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') );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...