UNPKG

@imhonglu/pattern-builder

Version:

Type-safe regular expression pattern builder for TypeScript with fluent API

105 lines (104 loc) 2.67 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var pattern_builder_exports = {}; __export(pattern_builder_exports, { PatternBuilder: () => PatternBuilder }); module.exports = __toCommonJS(pattern_builder_exports); class PatternBuilder { constructor(source) { this.source = source; } anchor(position) { switch (position) { case "start": this.source = `^${this.source}`; break; case "end": this.source = `${this.source}$`; break; default: this.source = `^${this.source}$`; break; } return this; } group() { this.source = `(${this.source})`; return this; } nonCapturingGroup() { this.source = `(?:${this.source})`; return this; } lookahead() { this.source = `(?=${this.source})`; return this; } negateLookahead() { this.source = `(?!${this.source})`; return this; } lookbehind() { this.source = `(?<=${this.source})`; return this; } negateLookbehind() { this.source = `(?<!${this.source})`; return this; } // quantifier oneOrMore() { this.source = `${this.source}+`; return this; } zeroOrMore() { this.source = `${this.source}*`; return this; } exact(count) { this.source = `${this.source}{${count}}`; return this; } repeat(min, max) { this.source = `${this.source}{${min},${max !== null && max !== void 0 ? max : ""}}`; return this; } optional() { this.source = `${this.source}?`; return this; } clone() { return new PatternBuilder(this.source); } toString() { return this.source; } toRegExp(...flags) { const pattern = this.toString(); const flag = flags.join(""); try { return new RegExp(pattern, flag); } catch (error) { throw new Error(`Failed to create RegExp from "${pattern}" with flags "${flag}"`, { cause: error }); } } }