匹配Google Apps脚本中的两个连续空格

问题描述 投票:1回答:1

我正在尝试使用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}", " ")但是它也匹配更大的空间组中的两个空格。

regex google-apps-script google-docs
1个回答
1
投票

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

因此,我建议以下各种替换的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');
}
© www.soinside.com 2019 - 2024. All rights reserved.