如何在 replaceText 中使用带有正则表达式元字符的字符串作为正则表达式?

How to use string with regex metacharacters as regex in replaceText?

我有一些代码在 document 中搜索标签并将其替换为特定的合并字段。在我的标签中有 |(管道符号)之前,这段代码工作正常。

由于某种原因,搜索只部分匹配。我怀疑这与它认为我传递的变量是正则表达式模式而不是文字字符串有关,但我不确定如何强制将其视为字符串。我使用 replaceText,它接受正则表达式作为字符串。

bodyObject.replaceText(Regex<String>, Replacement<String>);

我是这样使用的:

bodyObject.replaceText(markup, dataRow[headerIndex]);

在上面的示例中,等于“{{ tag | directive }}”的标记将导致部分匹配。

如果我们希望标记是纯文本,您可以在 replaceText 中将其作为参数传递时转义整个变量。我没有发现这会破坏你拥有的任何东西,除了 replaceText 行之外你不会修改任何其他东西。

样本:

function escapeString() {
  var bodyObject = DocumentApp.getActiveDocument().getBody();
  
  markup = "{{ tag | directive }}";
  
  newString = "<mergeField>";
  // escape any non word character ($& = whole matched string)
  bodyObject.replaceText(markup.replace(/\W/g, "\$&"), newString);
}

之前:

之后:

参考:

.replaceText() supports and re2 supports \Q...\E:

\Q...\E literal text ... even if ... has punctuation

所以你可以使用:

bodyObject.replaceText(String.raw`\Q${markup}\E`, dataRow[headerIndex]);

这会将 \Q...\E 中的所有内容都视为文字字符。