
[英]Google Apps Script for Multiple Find and Replace in Google Sheets
[英]Google Apps Script Multiple Find and replace regex in Google Sheets
我正在嘗試編寫Google Apps腳本,以使用正則表達式在Google表格中查找首字母縮寫詞和縮寫。 我有數十個首字母縮寫詞需要在數千行中替換。 我從堆棧溢出中發現了一些很棒的代碼,可以幫助查找和替換字符串,但是對於批量查找正則表達式並替換為字符串沒有任何幫助。
通過嘗試查找和替換首字母縮寫詞和縮寫,我發現我需要使用帶有邊界標志的正則表達式來防止它在較大的單詞中替換3個字母匹配項。 在下面的示例中,我正在尋找首字母縮寫詞“ xyz”,並將其替換為“ XYZ”。 但是不希望它與單詞“ 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;
}
}
據我所知,它僅與字符串而不是正則表達式有關,與'.replace'有關。 我嘗試使用雙引號轉義'\\ b'。
任何幫助,將不勝感激。
使用正則表達式而不是字符串:
replaceInSheet(values, /\bxyz\b/g, 'X Y Z');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.