Google Apps Script findText() method not working with RegEx patterns

I’m trying to use regular expressions to search through a Google Document that contains markdown-style code blocks marked with triple backticks. However, when I run my script, the findText() method keeps returning null instead of finding the text I’m looking for.

Here’s what I’m working with:

var pattern = '`{3}([\s\S]*?)`{3}'; // Pattern to match text between triple backticks
var searchResult = document.findText(pattern); // This returns null

I think the issue might be related to some regex syntax that isn’t compatible with the RE2 engine that Google uses, but I can’t figure out exactly what’s wrong. Has anyone run into similar problems with findText() and regex patterns? What am I missing here?

Yeah, ran into this exact issue last month. findText() is weird with multiline regex - try escaping the curly braces like \{3\} instead of {3}. Google Docs also handles line breaks strangely, so that’s probably where your pattern breaks. I gave up and went simpler - search for the triple backticks as plain text, then manually grab what’s between them.

This is a super common issue with Google Apps Script’s findText method. It’s not really about RE2 compatibility - it’s how the method handles multiline patterns and greedy matching.

I ran into the same thing extracting code blocks from docs. Here’s what worked: break it down into smaller pieces. Don’t try capturing everything between triple backticks at once. Instead, find the opening backticks first, then work from there to find the closing ones.

Also try using a non-greedy quantifier with a more specific character class. The [\s\S]*? pattern often breaks in document searches because it’s matching across what Google Docs treats as separate text runs internally.

Start simple - search for just the backticks to make sure they’re found, then build up your pattern complexity. The document structure can mess with how regex gets processed.

Google Apps Script’s findText() doesn’t support regex at all - just literal string matching. The docs aren’t super clear about this, which tripped me up initially.

You’ll need findText() for literal strings, then handle regex with regular JavaScript methods. Search for the opening triple backticks as plain text, grab that range, then extract and process the surrounding text with standard regex.

I work around this by pulling the full document text with getBody().getText(), running regex on that string, then using match positions to create ranges back in the document. More steps, but you get actual regex functionality that findText() can’t give you.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.