簡體   English   中英

Googles Apps腳本完全匹配

[英]Googles Apps Script exact match

我正在使用此腳本,但是它將替換T,A等的每個實例。如何獲取它以僅替換完全匹配項? 只要是字母T,別無其他。

function runReplaceInSheet(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Underlevel");
  //  get the current data range values as an array
  //  Fewer calls to access the sheet -> lower overhead 
  var values = sheet.getDataRange().getValues();  

  // Replace
  replaceInSheet(values, "/^T$/", '=image("https://i.imgur.com/Dxl893F.png")');
  replaceInSheet(values, 'A', '=image("https://i.imgur.com/omc7F9l.png")');
  replaceInSheet(values, 'R', '=image("https://i.imgur.com/12ZmSp3.png")');
  replaceInSheet(values, 'M', '=image("https://i.imgur.com/kh7RqBD.png")');
  replaceInSheet(values, 'H', '=image("https://i.imgur.com/u0O7fsS.png")');
  replaceInSheet(values, 'F', '=image("https://i.imgur.com/Hbs3TuP.png")');

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

謝謝:D

問題:

  • 字符串類型而不是正則表達式對象:您將字符串作為String#replace()第一個參數提供,並期望執行正則表達式類型。 "/^T$/"將被解釋為以/開頭,包含^T$並以/結束的字符串文字。

解:

  • 不帶正則表達式的正則表達式:正則表達式的文字不應使用"

片段1:

/^T$/    //or new RegExp('^T$')

片段2:

您也可以直接將.replace()與替換函數一起使用。

var range = sheet.getDataRange();
var replaceObj = {
  //to_replace: imgur id
  T: 'Dxl893F',
  A: 'omc7F9l',
};
var regex = new RegExp('^(' + Object.keys(replaceObj).join('|') + ')$', 'g');// /^(T|A)$/
function replacer(match) {
  return '=image("https://i.imgur.com/' + replaceObj[match] + '.png")';
}
range.setValues(
  range.getValues().map(function(row) {
    return row.map(function(original_value) {
      return original_value.toString().replace(regex, replacer);
    });
  })
);

參考文獻:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM