DIY一个正则匹配引擎

class MyRegex { static getInstance(...arg) { if (!MyRegex.instance) MyRegex.instance = new MyRegex(arg); return MyRegex.instance; } constructor() { console.log('运行一次') } test(){}}MyRegex.getInstance().test();matchOne(pattern, text) { return pattern === text;}matchOne。现在,我们要添加对更长长度的pattern和text字符串的支持。同样的,我们需要把问题简化下,暂时让我们仅考虑相同长度的pattern-text对。match(pattern, text) { return ( this.matchOne(pattern[0], text[0]) && this.match(pattern.slice(1), text.slice(1)) );}function match(){ ... match()}matchOne(pattern, text) {// 当pattern为空的时候,任意文字都是匹配的 if (!pattern) return true; // 当pattern不为空,但是text为空,返回false if (!text) return false; // 当pattern为.时,任意文字都是匹配的 if (pattern === ".") return true; return pattern === text;}match(pattern, text) { if (pattern === "") { return true; } else if (pattern === "$" && text === "") { return true; } else if (pattern[1] === "?") { return this.matchQuestion(pattern, text); } else if (pattern[1] === "*") { return this.matchStar(pattern, text); } else { return ( this.matchOne(pattern[0], text[0]) && this.match(pattern.slice(1), text.slice(1)) ); }} 赞 (0)
