如何为 google 文档替换 google 脚本中字母列表的所有元素

How to replace all elements of alphabetical list in google script for google doc

我想自动化一些文档编辑。现在,我正在尝试用 ~

替换不正确的测验列表元素

例如,假设我在文档中有以下内容,并且我已经使用 =.

标记了正确的选择
The capital of Norway is:
a. Haifa
=Oslo
c. Lund
d. the Hague
e. Manitoba

我想创建一个脚本来替换 a.、c.、d. 和 e。每个都有 ~

我试过创建一个如下所示的函数:

function incorrectAnswera(){
  var body = DocumentApp.getActiveDocument().getBody();
  body.replaceText("a.", "~");
}

但是它用 ~ 替换了“a”的每个实例和后面的字符。比如地球变成E~th.

Text.replaceText(searchPattern, replacement) uses regular expressions for the searchPattern, specifically Google's RE2 library.

作为正则表达式,a.会匹配字母“a”加上后面的任何字符,因为.是一个特殊的“通配符”匹配 any 字符的正则表达式中的字符。

作为正则表达式约定,可以用反斜杠去除.字符的特殊含义:\.。但是,由于 Apps 脚本实施采用 JavaScript 字符串作为输入,您必须(烦人地)添加 extra 反斜杠以获得所需的效果。

a\. 匹配字符序列“a”后跟句点。

这仍然会造成破坏,因为如果你有这句话

In the rain, I use an umbrella.

它将被替换为

In the rain, I use an umbrell~

要解决这个问题,我们需要指定 行以 我们的表达式开始,并且 ^ 字符是为此保留的。

^a\. 仅当该行以“a”开头后跟句点时才会替换。

实现您的既定目标:

I want to create a script that will replace a., c., d., and e. each with ~

您还需要使用一组字符来匹配,您可以使用 [].

定义这些字符

要按字面意思接受您的请求,集合应该是 [acde],但是由于您已经用 = 标记了正确答案,也许只是使用范围“a”到“ e" 会更好:[a-e](包括从 a 到 e 的所有 5 个字母)。

作为最后的细节,如果您想要在 a. 序列前面添加白色 space 的选项,您可以使用 \s* 来表示“零个或多个白色 space 个字符”,但是替换可能会删除白色 space。

// mark the start of the correct answer with a "=" before running this function
function markIncorrectAnswers() {
  DocumentApp.getActiveDocument().getBody()
    .replaceText("^\s*[a-e]\.", "~");
}