diff --git a/extensions/text.js b/extensions/text.js index dd77ac882a..f701a0a2c8 100644 --- a/extensions/text.js +++ b/extensions/text.js @@ -296,10 +296,11 @@ }, }, { - opcode: "countRegex", + opcode: "matchRegexJSON", blockType: Scratch.BlockType.REPORTER, text: Scratch.translate({ - default: "count regex /[REGEX]/[FLAGS] in [STRING]", + default: + "matches of [STRING] using regex /[REGEX]/[FLAGS] as array", description: "/[REGEX]/ is supposed to match the syntax that some actual programming languages used for regular expressions.", }), @@ -310,11 +311,11 @@ }, REGEX: { type: Scratch.ArgumentType.STRING, - defaultValue: "[AEIOU]", + defaultValue: "(.) (.{2})", }, FLAGS: { type: Scratch.ArgumentType.STRING, - defaultValue: "i", + defaultValue: "g", }, }, }, @@ -341,6 +342,29 @@ }, }, }, + { + opcode: "countRegex", + blockType: Scratch.BlockType.REPORTER, + text: Scratch.translate({ + default: "count regex /[REGEX]/[FLAGS] in [STRING]", + description: + "/[REGEX]/ is supposed to match the syntax that some actual programming languages used for regular expressions.", + }), + arguments: { + STRING: { + type: Scratch.ArgumentType.STRING, + defaultValue: "Hello world!", + }, + REGEX: { + type: Scratch.ArgumentType.STRING, + defaultValue: "[AEIOU]", + }, + FLAGS: { + type: Scratch.ArgumentType.STRING, + defaultValue: "i", + }, + }, + }, "---", @@ -637,6 +661,38 @@ return ""; } } + matchRegexJSON(args, util) { + // matchRegex but it returns an array + try { + const string = Scratch.Cast.toString(args.STRING); + const uncleanRegex = Scratch.Cast.toString(args.REGEX); + const flags = Scratch.Cast.toString(args.FLAGS); + + // Cache the last matched string + if ( + !( + matchCache && + matchCache.string === string && + matchCache.regex === uncleanRegex && + matchCache.flags === flags + ) + ) { + const newFlags = flags.includes("g") ? flags : flags + "g"; + const regex = new RegExp(uncleanRegex, newFlags); + + matchCache = { + string, + regex: uncleanRegex, + flags, + arr: string.match(regex) || [], + }; + } + return JSON.stringify(matchCache.arr) || "[]"; + } catch (e) { + console.error(e); + return ""; + } + } countRegex(args, util) { // Fill cache