带有replaceAllText的RegEx Google Apps脚本 问题:解决方案:代码示例:注意:

问题描述

我尝试用replaceAllText替换Google幻灯片中的某些文本,如果我提供了字符串,效果很好,但是找不到正则表达式的解决方案。

我要更改的是:

N = 500

我用replaceAllText尝试过的正则表达式版本:

/N [=,0-9]*/
"N [=,0-9]*"
"N = [0-9]*"
"N = \d*"
/N = \d*/

但没有任何效果

如何在正则表达式中使用replaceAllText

解决方法

问题:

replaceAllText不支持正则表达式,但完全匹配子字符串。

解决方案:

您应该改用find(pattern)

查找(模式):返回与当前文本范围内的搜索模式匹配的所有范围。搜索区分大小写。

代码示例:

例如,如果您要查找和替换演示文稿中的所有正则表达式匹配项,则可以执行以下操作:

// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0

function findAndReplace() {
  var pres = SlidesApp.getActivePresentation();
  var slides = pres.getSlides();
  const pattern = "N = \\d*";
  slides.forEach(slide => { // Iterate through every slide in the presentation
    slide.getShapes().forEach(shape => { // Iterate through every shape in the slide
      const textRange = shape.getText(); // Get shape text
      const matches = textRange.find(pattern); // Find matches
      matches.forEach(match => match.setText("REPLACED TEXT")); // Replace text
    });               
  });
}

注意:

  • 上面的代码示例(N = \\d*)中的表达式有两个反斜杠,因为正如文档所说,any backslashes in the pattern should be escaped。可能的替代方法可以是N = [0-9]*

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...