【问题标题】:Matching exactly two consecutive spaces in Google Apps Scripts准确匹配 Google Apps 脚本中的两个连续空格
【发布时间】:2019-02-19 04:13:30
【问题描述】:

我正在尝试使用 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”而不是“character character

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

【问题讨论】:

  • 你不能只做replaceText(" ", " ")吗?
  • @Jack Bashford 不会只匹配一个空格吗?
  • 这是 StackOverflow 的注释 markdown 语法的问题,它似乎用单个空格替换重复的键入空格。不确定是否有解决方法。 (我确定@Jack 在评论框中输入了两个空格)例如foo bar foo 和bar 之间输入了5 个空格@
  • @CertainPerformance 在那种情况下仍然没有,因为我在使用replaceText(“”,“”)时出错,所以我使用replaceText(“{2}”,“”),应该是一样的.问题在于它还匹配更大空间组中的两个连续空间,这是我不想要的。
  • 如果字母和数字之间必须出现空格,请尝试"\b {2}\b"

标签: regex google-apps-script google-docs


【解决方案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');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多