首页 > 解决方案 > 在 Google Docs 中查找并格式化所有以集合字符串开头的单词

问题描述

我在 Google Apps Script 中创建了一个函数,用于搜索 Google Docs 中的所有单词并将它们的颜色更改为所需的颜色。它需要输入:文档 ID、所需颜色和要查找的单词。

但是,我真正需要的是一个函数,它可以找到所有以特定字符串开头的单词。例如,“将所有以 # 开头的单词更改为蓝色”。我试着弄乱,findText()但没有运气。关于如何修复下面的功能来做我需要的任何想法?谢谢!

目前,我的功能如下所示:

 function colorTheWords(findMe,color,documentID) {

  //color input must be formatted in CSS notation like '#ffffff'
  
  //documentID must be formated as text in between ''
  
  //findMe word must be formatted as ''
  
  //open doc
  var document = DocumentApp.openById(documentID);
  var body = document.getBody();
  var foundElement = body.findText(findMe);

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

    // Change the current color to the desired color
    foundText.setForegroundColor(start, end, color);

    // Find the next match
    foundElement = body.findText(findMe, foundElement);
  }

} 

标签: google-apps-scriptgoogle-docs

解决方案


您遇到的主要问题是findText不使用普通的正则表达式,而是使用一种称为re2的风格。这有一些细微的变化和限制。如果要查找以特定字符串或字符开头的所有单词,则应使用以下表达式:

#([^\s]+)

推荐阅读