From 0b163e8ffd7b1d5786befcc84c4f28cecd247bd0 Mon Sep 17 00:00:00 2001 From: xeals Date: Thu, 27 Apr 2023 11:57:44 +1000 Subject: [PATCH] escape regex tokens --- calc.js | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/calc.js b/calc.js index 2b98e1b..97accba 100644 --- a/calc.js +++ b/calc.js @@ -12,6 +12,14 @@ import { createToken, Lexer } from "chevrotain"; const gen = Generations.get(9); +/** + * @param {string} text + * @return {string} + */ +function escapeRegExp(text) { + return text.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} + /** * Creates a lexer. * @@ -27,20 +35,28 @@ function buildLexer() { const Item = createToken({ name: "Item", - pattern: new RegExp([...gen.items].map((i) => i.name).join("|")), + pattern: new RegExp( + [...gen.items].map((i) => escapeRegExp(i.name)).join("|") + ), }); const Ability = createToken({ name: "Ability", - pattern: new RegExp([...gen.abilities].map((a) => a.name).join("|")), + pattern: new RegExp( + [...gen.abilities].map((a) => escapeRegExp(a.name)).join("|") + ), }); const Pokemon = createToken({ name: "Pokemon", - pattern: new RegExp([...gen.species].map((s) => s.name).join("|")), + pattern: new RegExp( + [...gen.species].map((s) => escapeRegExp(s.name)).join("|") + ), }); const Move = createToken({ name: "Move", - pattern: new RegExp([...gen.moves].map((m) => m.name).join("|")), + pattern: new RegExp( + [...gen.moves].map((m) => escapeRegExp(m.name)).join("|") + ), }); const whitespace = createToken({