Google apps script 谷歌文档中的搜索和颜色 函数searchandcolorinded(){ var doc=DocumentApp.getActiveDocument(); var textToHighlight=newregexp('\(\d{0,4}\)); var highlightStyle={}; highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR]=“FF0000”; var-paras=doc.getparations(); var textLocation={}; var i; 对于(i=0;i

Google apps script 谷歌文档中的搜索和颜色 函数searchandcolorinded(){ var doc=DocumentApp.getActiveDocument(); var textToHighlight=newregexp('\(\d{0,4}\)); var highlightStyle={}; highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR]=“FF0000”; var-paras=doc.getparations(); var textLocation={}; var i; 对于(i=0;i,google-apps-script,Google Apps Script,AdamL是正确的 由于Google文档对findText方法的描述,我有点困惑: findText(搜索模式) 在元素的内容中搜索指定的文本模式 使用正则表达式 我还通过使用字符串对所有\进行转义,使其工作 function searchAndColorInRed() { var doc = DocumentApp.getActiveDocument(); var textToHighlight = new RegExp('\(\d{0,4}\)'); var highlightS

AdamL是正确的

由于Google文档对findText方法的描述,我有点困惑:

findText(搜索模式)

在元素的内容中搜索指定的文本模式 使用正则表达式

我还通过使用字符串对所有
\
进行转义,使其工作

function searchAndColorInRed() {
  var doc = DocumentApp.getActiveDocument();
  var textToHighlight = new RegExp('\(\d{0,4}\)');
  var highlightStyle = {};
  highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
  var paras = doc.getParagraphs();
  var textLocation = {};
  var i;

  for (i=0; i<paras.length; ++i) {
    textLocation = paras[i].findText(textToHighlight);
    if (textLocation != null && textLocation.getStartOffset() != -1) {
      textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
    }
  }
};
函数searchandcolorinded(){
var doc=DocumentApp.getActiveDocument();
var textToHighlight=“\\(\\d{0,4}\\)”;
var highlightStyle={};
highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR]=“FF0000”;
var-paras=doc.getparations();
var textLocation={};
var i;

对于(i=0;iI也无法使其工作…我只能在文档中突出显示带有斜杠的数字,然后是数字,然后是斜杠,例如:/234/并且我还可以在dox中匹配以下文本:/(234)/使用regex/(\d*)/(但是,如上所述,不是(234))我希望你能得到答案……我一直在尝试你的代码的一些变体和其他方法,但没有成功。不知道为什么:-/pourtant le regex est correct…,奇怪:-)我可能错了,但我相信findText()方法需要一个表示要搜索的正则表达式的字符串参数,而不是正则表达式对象。但是,是的,它似乎限制了您可以使用的内容。如果您将所有内容都放在字符类中而不是转义,我成功地使它工作:
var textToHighlight='[(][0-9]{0,4}[)];
很好地解决了问题。
function searchAndColorInRed() {
  var doc = DocumentApp.getActiveDocument();
  var textToHighlight = "\\(\\d{0,4}\\)";
  var highlightStyle = {};
  highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
  var paras = doc.getParagraphs();
  var textLocation = {};
  var i;

  for (i=0; i<paras.length; ++i) {
    textLocation = paras[i].findText(textToHighlight);
    if (textLocation != null && textLocation.getStartOffset() != -1) {
      textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
    }
  }
};