【问题标题】:What is the RegExMatch equivalent in Google Apps Script?Google Apps 脚本中的 RegExMatch 等效项是什么?
【发布时间】:2019-11-07 19:03:53
【问题描述】:

如何在应用程序脚本中获得 regexmatch 的等效项?

电子表格示例:

A1 = "ThisIsA2018Test"
B1 = "IsA(\d){1,4}Test"

REGEXMATCH(A1,B1) 返回真...

如何使用 Google 应用程序脚本匹配这个?

【问题讨论】:

    标签: javascript regex google-apps-script google-sheets


    【解决方案1】:

    Google Apps Script/JavaScript 中的 Google Sheets 内置函数 REGEXMATCH 的等价物是RegExp.prototype.test

    var A1 = "ThisIsA2018Test";
    var B1 = "IsA(\\d){1,4}Test"; // Please note that `\d` was escaped by adding a `\`
    var test = new RegExp(B1).test(A1);
    console.info(test);

    【讨论】:

      【解决方案2】:

      根据this documentation,我猜你的表情还可以,

      REGEXMATCH("ThisIsA2018Test", "IsA[0-9]{1,4}Test")
      
      • 例如将 A1 复制并粘贴到 A2 中
      • 将 B1 复制并粘贴到 B2 中
      • 在 C2 中,=REGEXMATCH(A2, B2) 返回 true

      REGEXMATCH("ThisIsA2018Test", "IsNOTA[0-9]{1,4}Test")
      

      在 C3 中返回 FALSE

      演示

      const regex = /IsA[0-9]{1,4}Test/gm;
      const str = `ThisIsA2018Test`;
      let m;
      
      while ((m = regex.exec(str)) !== null) {
          // This is necessary to avoid infinite loops with zero-width matches
          if (m.index === regex.lastIndex) {
              regex.lastIndex++;
          }
          
          // The result can be accessed through the `m`-variable.
          m.forEach((match, groupIndex) => {
              console.log(`Found match, group ${groupIndex}: ${match}`);
          });
      }

      Please see the demo for additional explanation.

      【讨论】:

      • 问题是关于在 Google Apps 脚本上使用正则表达式。答案的第一部分是关于使用 GoogleSheets 内置函数,而不是 Google Apps Script,该演示使用了在 Google Apps Script 上没有很好实现的 JavaScript 功能,例如 const(它的工作原理与 var 非常相似)和其他默认情况下不支持箭头函数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多