google-apps-script - 带有replaceAllText的RegEx Google Apps脚本

标签 google-apps-script google-slides-api

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

我想要改变的是:

N = 500

我尝试使用 replaceAllText 的正则表达式变体:

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

但没有任何效果。

如何将 replaceAllText 与正则表达式一起使用?

最佳答案

问题:

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

解决方案:

您应该使用find(pattern)相反:

find(pattern): Returns all the ranges matching the search pattern in the current text range. The search is case sensitive.

代码示例:

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

// 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*) 有两个反斜杠,因为,正如文档所述,模式中的任何反斜杠都应该被转义。可能的替代方案是 N = [0-9]*

关于google-apps-script - 带有replaceAllText的RegEx Google Apps脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64588039/

相关文章:

api - 如何使用 google-apps-script 制作媒体推文?

google-apps-script - 谷歌脚本在哪里执行?在服务器还是客户端?

google-apps-script - 如何获取当前工作表名称?

google-apps-script - 有没有办法在 Google 幻灯片中使用 Google Apps 脚本获取/添加动画到对象?

charts - 如何自动更新链接到 Google 表格的图表?

google-apps-script - 在 Google 云端硬盘中更新图片时更新 Google 幻灯片中的图片

google-apps-script - 通过 Google Apps Scripts 获取 Google 演示幻灯片的布局显示名称

javascript - 自动将 Google 表格中单元格内容大写的脚本?

javascript - 如何更改谷歌幻灯片中链接对象指向的工作表?

google-apps-script - 如何使用 Apps 脚本将 Google 表格内容粘贴到 Google 幻灯片中?