Use RegEx in Google Doc Apps Script to Replace Text

試著忘記壹切 提交于 2019-12-11 02:28:58

问题


There is a line in a Google Doc that has a time and date stamp. I have written the following code using a regex to replace that line with the current time/date, but I am not sure why this isn't working.

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'));

}

If I replace the "regExp" in the document.replaceText line with, for example, "3:43 PM January 22, 2019", the code correctly replaces that with the updated date/time, but it is not able to replace the matched regex. Any ideas? Thanks!


回答1:


You should pass the regex with the help of a string literal:

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

The replaceText documentation explains it:

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.



来源:https://stackoverflow.com/questions/54331588/use-regex-in-google-doc-apps-script-to-replace-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!