Google Apps脚本中的RegExMatch等效项是什么?

时间:2019-06-25 21:55:23

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

如何在应用脚本中获得正则表达式的等效内容?

电子表格示例:

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

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

我如何使用Google Apps脚本来匹配它?

2 个答案:

答案 0 :(得分:1)

Google Apps脚本/ 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);

答案 1 :(得分:0)

根据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

enter image description here

演示

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.