google-apps-script - 带有 replaceAllText 的正则表达式 Google Apps 脚本
问题描述
我试图用 替换谷歌幻灯片中的一些文本,replaceAllText
如果我提供字符串它工作正常,但是我找不到正则表达式的解决方案。
我想改变的是:
N = 500
我尝试过的正则表达式变体replaceAllText
:
/N [=, 0-9]*/
"N [=, 0-9]*"
"N = [0-9]*"
"N = \d*"
/N = \d*/
但没有任何效果。
如何使用replaceAllText
正则表达式?
解决方案
问题:
replaceAllText不支持正则表达式,但完全匹配子字符串。
解决方案:
您应该改用find(pattern):
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]*
.
推荐阅读
- java - 如何读取文件并将其对象存储到我的自定义链表中?
- ios - CallKit 呼叫阻止扩展程序偶尔会自动禁用
- machine-learning - 从 Google 对象检测 ML 建议的边界框中查找文本
- reactjs - 当 React Hooks 中的 redux 状态更改时,道具不会更新
- apache-spark - 为什么在 Spark 中禁用和未记录自适应执行?
- ios - UIImage 获取 CVPixelBuffer 移除 Alpha
- javascript - 如何使用 intl-tel-input 的 utils.js 保存计数器代码?如何使用 javascript 提供的数据到 django 应用程序中?
- java - 在 Spring Boot JPA 中编辑对象值和使用 save() 时出现 MySQL java.sql.SQLSyntaxErrorException
- python - 使用 cv2 和 svm 的 setTermCriteria
- node.js - 可以看到视频流的开始,但没有别的。Node.js、MP4、HTML5。第一个 blob 中的文件签名