【发布时间】:2014-02-25 19:15:41
【问题描述】:
我正在尝试使用findText 和正则表达式在一对两个星号(即**This text, please**)之间查找无法确定的文本数量,包括标点符号。然后脚本应该对星号和随附的文本起作用。我的代码如下:
function main() {
var search = body.findText('(\*\*)+([.*]+)+(\*\*)');
if (search === null) {
DocumentApp.getUi().alert('No text was found that required formatting.');
} else {
function second() {
if (search !== null) {
search = body.findText('(\*\*)+([.*]+)+(\*\*)');
search.setBold(true);
body.replaceText('\*\*','');
second();
} else {
DocumentApp.getUi.alert('Formatting completed!');
}
};
}
};
我正在假设findText 只找到搜索模式的第一个实例。
现在,我完全知道由于不支持捕获组,我的正则表达式将不起作用,但是还有什么其他方法可以“短语”,例如搜索?如果不能用单个正则表达式完成,是否可以通过三个单独的带有偏移量的搜索来做到这一点?
【问题讨论】:
-
您的 .findText 正则表达式对于双星号之间的匹配不正确。它应该更像:
\*\*(.*)\*\*. -
此外,.findText 将返回 true 或 false。你应该检查真假。不是“空”。
-
什么是.replaceText()?这是来自其他插件或脚本的功能吗?只使用 javascript
.replace()怎么样?和 search.setBold()?你在一个布尔值上调用 .setBold() (不管是什么)..你的代码有太多问题.. -
@MElliott 我首先尝试了初始代码,但如前所述,函数
.findText不支持捕获组。此外,.findText作为字符串值返回(这让我想知道这是否真的会按预期工作,以及可以使用哪些其他方法)。这里记录了正在使用的函数:developers.google.com/apps-script/reference/document/…
标签: javascript regex google-apps-script