仅对给定字符串的数字求和

Sum only numbers given a string

如何创建 Apps 脚本函数来仅对给定字符串的数字求和。我已经能够使用 Google Sheets:

中的这个常规公式来做到这一点
=SUM(SPLIT( LOWER(A1) , "abcdefghijklmnopqrstuvwxyz+$ " ))

但我无法理解如何在 Google Apps 脚本中执行此类操作。虽然我知道它的工作方式类似于 Javascript,但 Javascript 中的这个示例在 Google 表格的 Apps 脚本中不起作用。

function sumAmounts(str) {
  let nums = [];
  let sum = 0;

  for (let i = 0; i < str.length; i++) {
    if (!isNaN(Number(str[i]))) {
      nums.push(Number(str[i]));
    }
  }
  // console.log(nums);
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];
  }
  return sum;
}

// Test it
console.log(sumAmounts("foo5bar6cat1"));

字符串中数字的总和

function sumOnlyNumbersInAString() {
  const s ="A123N789Kyxtu9x6".split("");
  let sum = s.reduce((a,c) => {
    if(c.match(/\d/)) {//matches [0-9]
      a += Number(c);
    }
    return a;
  },0);
  Logger.log(sum);
}
Execution log
4:59:47 PM  Notice  Execution started
4:59:47 PM  Info    45.0
4:59:48 PM  Notice  Execution completed

另一种方法是假设连续的数字是多位数字

function sumOnlyNumbersInAString() {
  const m ="A123N789Kyxtu9x6".match(/\d+/g);
  let sum = m.reduce((a,c) => {
    a += Number(c);
    return a;
  },0);
  Logger.log(sum);
}

Execution log
5:08:14 PM  Notice  Execution started
5:08:15 PM  Info    927.0
5:08:16 PM  Notice  Execution completed

在后一种情况下,我们添加 123 + 789 + 9 + 6

Regular Expressions

regex syntax for GAS

您提供的代码正在运行,您只需创建另一个将调用 console.log(sumAmounts("foo5bar6cat1")); 的函数,因为 Apps 脚本只能在函数内执行代码。

您的代码应如下所示:

function sumAmounts(str) {
  let nums = [];
  let sum = 0;
  for (let i = 0; i < str.length; i++) {
    if (!isNaN(Number(str[i]))) {
      nums.push(Number(str[i]));
    }
  }
  for (let i = 0; i < nums.length; i++) {
    sum += nums[i];
  }
  return sum;
}


function main(){
  console.log(sumAmounts("foo5bar6cat1"));
}

输出:

注意: 确保在 Apps 脚本中将函数更改为 运行。 Debug 按钮旁边有一个下拉菜单,您可以在其中选择 运行.

的功能

此外,由于您的 sumAmounts(str) 函数中有一个 return 语句,您可以将它用作 Google Sheet 中的 Custom Function 来测试值。

示例:

Google 原生表格

虽然此公式不如 Apps 脚本中定义的单个公式清晰,但每次都会加载而不会出现任何问题。

=ArrayFormula(SUM(IFNA(REGEXEXTRACT(to_text(split(substitute(H1831,"$","~$"),"~")), "$([0-9.,]+)")*1)))

Apps 脚本

更新:此实现有效,但有时会出现加载错误。

虽然我真诚地感谢收到的所有意见和建议,但它们确实引导我朝着正确的方向前进;我能够通过以下方式解决我的问题。

这为我的案例提供了一个解决方案以及在 Google 表格中使用它的预览和自动建议。

/**
 * Adds only numbers in a cell.
 * 
 * @param {string} cell The cell of text selected.
 * @return The sum of only numbers of a given cell.
 * @customfunction
 */

function ADDNUMBERS(cell) {  
  var regex = /\d+([\.]\d+)?/g;

  const matches = cell.match(regex);
  
  nums = matches.map(Number);

  sum = nums.reduce((a,b) => {
    return a + b;
  });
  
  return sum
}

function main(){
  test = "Neighbor Notification Shipping Fees .50 + Building Permit Final Fees 8.78 + CC Fees";
  console.log(ADDNUMBERS(test))
}

Execution log
11:27:58 PM Notice  Execution started
11:27:59 PM Info    316.28
11:27:59 PM Notice  Execution completed

此函数解析我的字符串并创建一个仅匹配浮点数的正则表达式的数组。稍后数组中的所有元素都被转换为浮点数,最后,将 return 总和。

奖励是在公式上方创建 JSDoc 注释。

再次感谢所有快速输入。