我刚刚编写了一个简单的 Google Sheets 函数来修复一些 URL。当手动传递值数组时,此函数在浏览器中运行良好。从 Google 表格调用时,该函数对于每隔一行都会失败。
这不是数据问题,因为我可以通过将公式向下移动一行或为每个单元格单独调用它来使其适用于“失败”行。我认为这可能是谷歌表格内的regex
的问题。
var pattern = /^http:\/\/(.*\/\d\/.*)_(.*)\/(g\d+p.*)$/ig;
function encode(input) {
if (!input) return "";
if (input.map) {
return input.map(encode);
} else {
try {
// same error happens, at this location, w/ or w/o toString()
var matches = pattern.exec(input.toString());
return matches[1] + encodeURIComponent(matches[2]) + matches[3];
} catch (e) {
return "error=" + e.message + " value = [" + input + "] ";
}
}
}
编辑:为了让后面的人更清楚,当正则表达式位于“else”子句内时,这也会以同样的方式失败:
else {
var matches = /^(http:\/\/.*\/\d\/.*_)(.*)(\/g\d+p.*)$/ig.exec(input.toString());
... continues as normal
对于交替的数据行,我收到此错误消息:
error=Cannot read property "1" from null. value = [ http://... ]
我已经尝试过:
- 将正则表达式放入
try{}
- 将正则表达式放入
encode{}
函数中 - 编写两个单独的函数(一个用于执行 1 个值)
在失败的情况下,我有这样的数据:
- A1-A8 中有网址
- B1 的公式为“=encode(A1:A8)”
- B1、B3、B5、B7 中的数据计算完美
- B2、B4、B6、B8 中的数据出错(显示我的错误消息)
将公式移至单元格“B2”并输入 =encode(A2:A8)
会导致所有“失败”行进行计算,而其他行则失败!
最佳答案
简短的答案(正如您对OP的评论所证实的那样)是从正则表达式中删除最后的“g”(全局标志)。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Syntax regexObj.exec(str)
Parameters str The string against which to match the regular expression.
...
If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression's lastIndex property (test() will also advance the lastIndex property).
所以看来,当您打算继续在同一字符串中搜索匹配项时,您确实应该只包含全局标志。
至于为什么它在其他环境中有效,我不确定。事实上,从上次中断的地方继续搜索似乎有点奇怪,即使您正在将 exec
应用于一个全新的字符串。也许 GAS 中的实现有点“偏离”——有更多知识的人可能能够对此发表评论。
关于regex - 在范围内使用时,带正则表达式的 Google Sheets 自定义函数在交替行上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272197/