在 Google Doc Apps 脚本中使用 RegEx 替换文本

Use RegEx in Google Doc Apps Script to Replace Text

Google 文档中有一行带有时间和日期戳。我使用正则表达式编写了以下代码,用当前 time/date 替换该行,但我不确定为什么这不起作用。

function UpdateDate() {

  var document = DocumentApp.getActiveDocument();
  var date = new Date();

  var regExp = /[0-9]{1,2}:[0-9]{2} [A-Z]{2} [A-Za-z]* [0-9]{1,2}, [0-9]{4}/;
  document.replaceText(regExp, Utilities.formatDate(date, 'America/Denver', 'h:mm a MMMM dd, yyyy'));

}

如果我将 document.replaceText 行中的 "regExp" 替换为例如“2019 年 1 月 22 日下午 3:43”,代码会将其正确替换为更新后的 date/time,但它无法替换匹配的正则表达式。有任何想法吗?谢谢!

您应该在字符串文字的帮助下传递正则表达式:

var regExp = "[0-9]{1,2}:[0-9]{2} [A-Z]{2} [A-Za-z]* [0-9]{1,2}, [0-9]{4}";

replaceText 文档对其进行了解释:

The search pattern is passed as a string, not a JavaScript regular expression object. Because of this you'll need to escape any backslashes in the pattern.

This methods uses Google's RE2 regular expression library, which limits the supported syntax.