3

I'm applying RegEx search to a Google Document text with some markdown code block ticks (```). Running the code below on my doc is returning a null result.

var codeBlockRegEx = '`{3}((?:.*?\s?)*?)`{3}'; // RegEx to find (lazily) all text between triple tick marks (/`/`/`), inclusive of whitespace such as carriage returns, tabs, newlines, etc.
var reWithCodeBlock = body.findText(codeBlockRegEx); // reWithCodeBlock evaluates to 'null'

I suspect that there's some element of regex in my code that is not supported by RE2, but the documentation has not shed light on this. Any ideas?

2
  • The document is not shared. Please make it public. Commented May 2, 2017 at 16:08
  • If the texts span across paragraphs, it is not so straightforward. Try var codeBlockRegEx = /`{3}([\s\S]*?)`{3}/g;, but it may not work. Commented May 2, 2017 at 16:59

1 Answer 1

4

I received null as well- I was able to get the below to work using 3 ` surrounding the word test within a paragraph.

I did find this information: findText method of objects of class Text in Apps Script, extending Google Docs. Documentation says “A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.” In particular, it does not support lookarounds.

function findXtext() {
var body = DocumentApp.getActiveDocument().getBody();
  var foundElement = body.findText("`{3}(test)`{3}");

while (foundElement != null) {
    // Get the text object from the element
    var foundText = foundElement.getElement().asText();

    // Where in the element is the found text?
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();

    // Set Bold
    foundText.setBold(start, end, true);
  
   // Change the background color to yellow
    foundText.setBackgroundColor(start, end, "#FCFC00");

    // Find the next match
    foundElement = body.findText("`{3}(test)`{3}", foundElement);
   }
}

Sign up to request clarification or add additional context in comments.

1 Comment

See my solution for a document wide search & replace: stackoverflow.com/a/70636525/164374

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.