谷歌电子表格搜索零件,替换和删除



我正试图使用Tasker(一款为android开发的应用程序)启动一个项目。它有很多有用的插件,我偶然发现了谷歌电子表格插件。有了这个插件,我可以很容易地从电子表格中读取
但我的问题是在电子表格上写字。我想使用电子表格作为我的tasker应用程序的数据库。

这意味着它将把简单的值写入电子表格示例
A2=Nexus5/off:1:8:1
>A3=Nexus6/on:2:3:4

我现在正在尝试在谷歌脚本中编写搜索和替换脚本。我被卡住了
我想让它做的是,如果我的Nexus5打开,它将在1:8:1发送到A1 Nexus5/中的电子表格。

脚本必须在A列中搜索Nexus5/,并用新值替换单元格值。之后,它必须删除A1,以便可以输入新的输入。下面是我迄今为止得到的脚本,它可以搜索我在A1中输入的输入,并在列表中用test替换它。但我似乎不能只搜索第一部分。

function replaceInSheet(sheet, to_replace, replace_with) {
//get the current data range values as an array
var values = sheet.getDataRange().getValues();
//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;
}
//write the updated values to the sheet
sheet.getDataRange().setValues(values);
}
function onChange(e){
var sheet = SpreadsheetApp.getActiveSheet()
replaceInSheet(sheet,val,'test');
}

您想要使用正则表达式来破解这个难题。这里有一套全面的答案。

简而言之,将搜索设置为/^Nexus5//(使用原始regex声明,或者创建一个新的RegExp()对象)&只需使用string.replace(),然后根据需要将更新后的值写回。

例如

var myString = “Nexus5/1.2.3”;
var newValue = myString.replace(/^nexus5/.+/i, “my new value”); 

因此,我们在这里寻找一个以"Nexus5/"开头的字符串,并将其替换为"my new value"。(^将搜索锚定在字符串的开头,.+表示除行尾之外的1个或多个字符,我们需要转义斜线-/,因此在模式将搜索设置为不区分大小写后,它不会被解释为正则表达式的末尾和i。)我们现在可以使用电子表格的range.setValue()或range.setValues()方法将newValue写回源工作表。

最新更新