首页 > 解决方案 > 准确匹配 Google Apps 脚本中的两个连续空格

问题描述

我正在尝试使用精确匹配两个连续的空格DocumentApp.getActiveDocument().getBody().replaceText()并将它们替换为单个空格。

不幸的是,它只支持一些正则表达式(https://github.com/google/re2/wiki/Syntax)。

我已经尝试过DocumentApp.getActiveDocument().getBody().replaceText("[^ ] {2}[^ ]", " "),但这也与文本周围的字符相匹配。

我已经尝试过DocumentApp.getActiveDocument().getBody().replaceText("([^ ]) {2}([^ ])", "$1 $2"),但这会输出“$1 $2”而不是“字符 字符

我已经尝试过DocumentApp.getActiveDocument().getBody().replaceText(" {2}", " "),但这也匹配更大空间组中的两个空间。

标签: regexgoogle-apps-scriptgoogle-docs

解决方案


(对我来说)很难为所需的替换编写一个正则表达式,因为每次也替换周围的字符(非空格)。此外,在一般情况下,当空格位置位于字符串的开头或结尾时,我们应该考虑特殊情况。

因此,我建议以下各种替换的 2 个函数:

function replaceDoubleSpace() {
  var body = DocumentApp.getActiveDocument().getBody();
  var count = replaceWithPattern('^  $', body);
  Logger.log(count + ' replacement(s) done for the entire string');
  count = replaceWithPattern('[^ ]{1}  [^ ]{1}', body);
  Logger.log(count + ' replacement(s) done inside the string');
  count = replaceWithPattern('^  [^ ]{1}', body);
  Logger.log(count + ' replacement(s) done at the beginning of the string');
  count = replaceWithPattern('[^ ]{1}  $', body);
  Logger.log(count + ' replacement(s) done at the end of the string');
}


function replaceWithPattern(pat, body) {
  var patterns = [];
  var count = 0;
  while (true) {
    var range = body.findText(pat);
    if (range == null) break;
    var text = range.getElement().asText().getText();
    var pos = range.getStartOffset() + 1; 
    text = text.substring(0, pos) + text.substring(pos + 1);
    range.getElement().asText().setText(text);
    count++;
  }
  return count;
}

当然,第一个函数可能会被简化,但在这种情况下它变得不太可读:

function replaceDoubleSpace() {
  var body = DocumentApp.getActiveDocument().getBody();
  var count = replaceWithPattern('^  $|[^ ]{1}  [^ ]{1}|^  [^ ]{1}|[^ ]{1}  $', body);
  Logger.log(count + ' replacement(s) done');
}

推荐阅读