简体   繁体   中英

Google Apps Script Multiple Find and replace regex in Google Sheets

I'm trying to write a Google Apps Script to find acronyms and abbreviations within Google sheets using regular expressions. I have dozens of acronyms that need to be replaced over thousands of rows. I have found some great bits of code from stack overflow that help find and replace strings, but nothing for bulk finding regex and replacing with strings.

With trying to find and replace acronyms and abbreviations I found I needed to use regex with the boundary flag to prevent it replacing 3 letter matches within bigger words. In the example below, I'm looking for the acronym "xyz" and to replace it with "XYZ". But don't want it do match on the word "abc xyz def".

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;
  }
}

From my little understanding it's to do with '.replace' only working with Strings and not Regular expressions. I've tried escaping the '\\b', using double quotes.

Any help would be appreciated.

使用正则表达式而不是字符串:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM