如果string.match()不匹配,为什么要取消执行Google Apps脚本?

如果string.match()不匹配,为什么要取消执行Google Apps脚本?

问题描述:

如果我在Google表格中使用以下功能,则不会返回未找到"值. 日志告诉我:执行已取消".

if I use the following function within Google Sheets it doesn't return the value "not found". The logs tell me: "Execution cancelled".

这发生在以下行:

var found = text.match(re);

如果我将searchText更改为"abc",则它就像一个超级按钮.

If I change searchText to "abc" it works like a charme.

function example()
{
  var text = "abc cba";
  var searchText = "abcd";

  var re = new RegExp(searchText,"g");

  var found = text.match(re);

  if (found === undefined) { 
    return "not found";
  }
  else {
    return found;
  }
} 

为什么脚本执行被取消,并且如何通过不使用regex两次来防止这种行为,例如在 match()之前的 text.search(re)与if 组合?

Why is the script execution cancelled and how can I prevent this behavior without using the regex twice by using e.g. text.search(re) combined with if before the match() ?

原因:

string.match的返回值,

一个数组,其内容取决于是否存在全局(g)标志;如果找不到匹配项,则为 null .

null !== undefined

因此,当它为null时,else语句将执行并将null返回到工作表. 执行已取消"是无关紧要的,并且可能来自旧日志 问题

So, when it's null, the else statement executes and returns null to sheet. The "execution cancelled" is irrelevant and probably from old logsissue

使用null来比较返回值.

Use null to compare return value.

if (found === null) {