【问题标题】:Google Apps Script Multiple Find and replace regex in Google SheetsGoogle Apps 脚本多个在 Google 表格中查找和替换正则表达式
【发布时间】:2019-05-06 02:16:50
【问题描述】:

我正在尝试编写一个 Google Apps 脚本,以使用正则表达式在 Google 表格中查找首字母缩写词和缩写词。我有几十个首字母缩略词需要在数千行中替换。我从堆栈溢出中发现了一些有助于查找和替换字符串的重要代码,但对于批量查找正则表达式和替换字符串没有任何帮助。

在尝试查找和替换首字母缩略词和缩写时,我发现我需要使用带有边界标志的正则表达式来防止它替换更大单词中的 3 个字母匹配。在下面的示例中,我正在寻找首字母缩略词“xyz”并将其替换为“X Y Z”。但不希望它匹配单词“abcxyzdef”。

function runReplaceInSheet(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheetName");
  var values = sheet.getDataRange().getValues();  

  // Replace Acronyms
  replaceInSheet(values, '\bxyz\b', 'X Y Z');

  // Write all updated values to the sheet, at once
  sheet.getDataRange().setValues(values);
}

function replaceInSheet(values, to_replace, replace_with) {
  //loop over the rows in the array
  for(var row in values){
    //use Array.map to execute a replace call on each of the cells in the row.
    var replaced_values = values[row].map(function(original_value) {
      return original_value.toString().replace(to_replace,replace_with);
    });

    //replace the original row values with the replaced values
    values[row] = replaced_values;
  }
}

据我所知,它与“.replace”有关,仅适用于字符串而不适用于正则表达式。我尝试使用双引号转义“\b”。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript arrays regex string object


    【解决方案1】:

    使用正则表达式代替字符串:

    replaceInSheet(values, /\bxyz\b/g, 'X Y Z');
    

    【讨论】:

    • 非常感谢。我不敢相信答案就这么简单。我不会告诉你我花了多长时间试图解决这个问题!
    • 没问题@Pommelhorse,总是乐于提供帮助。
    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-11
    • 2013-06-02
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多