gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:40:32 25 4
gpt4 key购买 nike

我试图用 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* )有两个反斜杠,因为正如文档所说, any backslashes in the pattern should be escaped .一个可能的选择是 N = [0-9]* .
  • 关于google-apps-script - 带有 replaceAllText 的 RegEx Google Apps 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64588039/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com