问题描述
我尝试用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]*
。