Google表格脚本通配符

时间:2016-12-18 10:50:24

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

我知道我可以使用通配符,例如;

=COUNTIF(A:A ; "*text*")

如果A1包含" text"。

,我想运行我的代码

A1 ="测试文字"

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:4)

对于Google Apps脚本,您可以使用正则表达式。如果您在应用程序脚本中对其进行硬编码,则正斜杠包围的任何语句都会被解释为正则表达式:

/.*text.*/

请注意,在RegExps中使用的通配符略有不同:您需要在星号.之前加一个点*
COUNTIF()*text* 正则表达式
/.*text.*/

所以快速脚本看起来像这样:

function matchText(text){
    try {
        var pattern = /.*text.*/;
        var isMatch = text.match(pattern)[0];
        return isMatch
    } catch (e) {
    return e.toString();
  }
};

广义自定义函数:

function matchText(text,pattern){
    try {
        var isMatch = text.match(pattern)[0];
        return isMatch
    } catch (e) {
    return e.toString();
  }
};

您仍然可以使用regexextract或regexmatch使用本机公式执行此操作,这始终是我的最爱。请记住使用正确的正则表达式通配符表示法:星号前面的点:.*。或者只使用text本身,它会自动找到它的任何实例:

enter image description here

答案 1 :(得分:0)

=IF(COUNTIF(A1, "*text*"), "your code here", "Code not run: A1 doesn't contain 'text'")

这是你的想法 - 公式代码?或者您想使用Google Apps Script

(对于这个,可能有一个比COUNTIF()更直观命名的功能,但它可以解决这个问题。)

答案 2 :(得分:0)

我的解决方案:

 if(test.indexOf("2,")>-1)
{
    my code goes here
    }