在Google文档电子表格中,如何索引REGEXEXTRACT返回的数组

时间:2012-10-05 17:48:37

标签: google-apps-script google-docs google-sheets

我正在尝试索引REGEXEXTRACT的结果,以提取作为路径的文本字符串的特定部分。如何访问特定匹配项。

  A1                                          A2
  ------------------------------------        -----------
  =REGEXEXTRACT($B$2,"/[A-Za-z_-]+/")         /a/b/c/d.txt

上面的公式将第一个数组值“/ a /”放入单元格A1,如何访问数组中的第4个或最后一个值?

1 个答案:

答案 0 :(得分:0)

如果您坚持使用REGEXTRACT()来突破您的路径,您可能会发现以下资源有用:

但是,在Google电子表格中,访问路径特定部分的最有效方法是: filename字符串是在嵌入式脚本中使用自定义函数。我假设你熟悉应用程序脚本编程;见Building Your First Script

以下代码包含两个脚本,一个构建在另一个脚本上。例如,调用pathExtract()将返回给定路径字符串的指定段。

/**
 * Split path into parts, return in array. If path started
 * at 'root', first part will be "/". This function may be used
 * as a custom function in Google Spreadsheets.
 *
 * @var {string} path   The search path, e.g. "/a/b/c/d.txt"
 * @return {array}      Result of splitting path at "/". 
 */
function pathSplit( path ) {
  var arr = path.split('/');
  if (path[0] === "/") {
    arr[0] = "/";
  }
  return ( arr );
}

/*
 * Get a portion of a path string. To match INDEX() function,
 * the parameter index is 1-based. Requesting index 0 will
 * result in the last element from the string. This function
 * may be used as a custom function in Google Spreadsheets.
 *
 * @var {string} path   The search path, e.g. "/a/b/c/d.txt".
 * @var {number} index  1-n, the element to extract. 0 for last.
 * @return {string}     Element [index] from path, or *ERROR*.
 */
function pathExtract( path, index ) {
  var result = "*ERROR*";
  var pathArray = pathSplit( path );
  if (index >= 1 && index <= pathArray.length) {
    result = pathArray[index-1];
  }
  if (index === 0) {
    result = pathArray[pathArray.length-1];
  }

  return ( result );
}

以下是您可以对添加到电子表格中的脚本执行的操作的几个示例: Formulas Shown

Results Shown