apps script findText for docs

不问归期 提交于 2019-12-07 22:53:44

问题


I know that the findText function for Google Doc elements doesn't use regular regex (it uses RE2, instead). I'm coming up against a regex issue where a validated, relatively simple, and seemingly supported regex block is paradoxically returning a null result in Apps Scripts.

Wondering if anyone can spot/explain the reason. Thanks!


I'm applying the code below to a block of text with some markdown code block ticks (```). The RegEx returns correct results when I paste the regex shown below into regexer.com with a similar code block. However, running the code below on my doc is returning a null result.

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?

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'


回答1:


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


来源:https://stackoverflow.com/questions/43741973/apps-script-findtext-for-docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!