skip to Main Content

I’m trying to use the findText() function of the DocumentApp class to get the position of some text inside a Google Docs. To do so, I’m using a Regex (RE2) expression. I want it to find the following sequences: $$anyCharacterHere$$ ; basically anything enclosed in between $$ … $$. As there might be more than one of these sequences, we have to tell the regex to match any sequence of this type without any "$" inside.

I’ve tried using the following:

const re2 = new RegExp("\$\$.*(?!\$)\$\$");
let range = docBody.findText(re2)

but it says that this is an invalid expression. I tried changing the backslashes and that kind of things, but couldn’t get any further.

The goal I want to achieve is, for example, in this text:

Thi is a $$text$$ to show an $example$$ of how the $$regex$$ $$$hould$$ work.

the regex should find: $$text$$ and $$regex$$.

2

Answers


  1. An alternative is given below where, your sample string is modified so that the searched strings can be at the beginning or in the middle or at the end of the sentence and also space characters can be involved in them.

    A sample string may be like this:

    $$Test at the beginning$$ and this is $$a text$$ to show an $example$$ of how the $$regex$$ $$$hould$$ work.

    function myFunction() {
      const doc = DocumentApp.getActiveDocument();
      const matches = doc
        .getBody()
        .getText()
        .match(/(?<=^|s)([$]{2}[^$]+[$]{2})/g);
    
      if (!matches || matches.length == 0) return;
    
      var out=[];
    
      for (var i=0; i<matches.length; i++){
        out.push(matches[i]);
      }
    
      Logger.log(out);
      }
    

    Screenshot of the console is given below:

    enter image description here

    Login or Signup to reply.
  2. Capturing all segments of strings enclosed with double dollar signs $$, while ignoring any single dollar signs $.

    const re2 = "\$\$[^$]+\$\$";
    let range = docBody.findText(re2);
    

    Reference:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search