【问题标题】:Retrieve data from a specific column based on multiple criteria (comma separated values) in Google Sheets根据 Google 表格中的多个条件(逗号分隔值)从特定列中检索数据
【发布时间】:2021-07-27 14:20:17
【问题描述】:

我正在尝试制作一个 Google 表格公式,它根据多个条件(逗号分隔)单元格匹配单元格中的单词并返回特定值。

Sheet1 包含短语和公式:

Phrases Formula
fruit bat {formula}
fruit bats {formula}
fruitbat {formula}
big fruit bat {formula}
fruit bat eating orange {formula}
orange fruit {formula}
apple is a good fruit {formula}
i like pie {formula}
pies for lunch {formula}
apple pie is better {formula}
juice from apples {formula}

Sheet2 搜索值(逗号分隔)和对应的返回值:

Comma-separated search values Return Value
fruit, bat Animal - Bats
fruit, orange, bat Animal - Orange bat
orange, fruit Food - Orange
apple, fruit Food - Apple
pie Food - Pie
apple, pie Food - Apple Pie
juice, apple Beverage - Apple

我希望 Sheet1 最终看起来像这样:

Phrases Formula
fruit bat Animal - Bats
fruit bats Animal - Bats
fruitbat Animal - Bats
big fruit bat Animal - Bats
fruit bat eating orange Animal - Orange bat
orange fruit Food - Orange
apple is a good fruit Food - Apple
i like pie Food - Pie
pies for lunch Food - Pie
apple pie is better Food - Apple Pie
juice from apples Beverage - Apple

现在我的公式如下所示: =IFNA(VLOOKUP(IFNA(REGEXEXTRACT(LOWER(A2); LOWER(TEXTJOIN("|"; 1; SORT(Sheet2!A:A; 1; 0))))); Sheet2!A:B; 2; 0))

公式正确返回短语“我喜欢馅饼”和“午餐馅饼”的“食物 - 馅饼”。它在短语“apple pie is better”上错误地返回“Food - Pie”,并且所有其他行都是空的。

是否可以修改当前公式,使其与搜索逗号分隔值兼容?

注意匹配应该是通配符,不依赖空格。

【问题讨论】:

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


    【解决方案1】:

    当且仅当由于其他答案不可用而可以选择自定义公式时,请参阅下面的代码。

    代码:

    function getRegexMatch(string, exprs) {
      // sort descending based on search length to get max matches
      exprs = exprs.sort(function(a, b){
        return b[0].length - a[0].length;
      });
      // filter pattern where number of matches is equal to number of search values
      var output = exprs.filter(function([expr, value]){ 
        var patterns = expr.split(", ");
        var result = patterns.filter(function(pattern) {
          if(RegExp(pattern).exec(string))
            return true;
        });
        if (patterns.length == result.length)
          return true;
      });
      // return the value of max match pattern
      return output[0][1];
    }
    

    输出:

    注意:

    • 搜索-返回值对在处理之前根据其搜索值的长度(较长的长度优先)进行排序,因为我们希望获得所有搜索值都与字符串匹配的返回值。这是为了防止返回并非所有搜索值都匹配的值以及匹配数少于搜索值数的其他搜索值(例如,fruit bat eating orange 返回Animal - Orange bat 而不是Animal - Bats,如果未排序,则首先出现)
    • 鉴于我们根据搜索值长度对搜索-返回值对进行排序(较长的长度在前),这意味着它总是会首先遇到可能的最佳匹配。
    • 所以当我们看到第一个匹配时,立即返回它。
    • 上面的代码每个单元格一个一个地调用,但可以修改为只调用一次并返回 A 列在 B 列上的所有匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 2020-08-23
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2018-08-10
      相关资源
      最近更新 更多