@imhonglu/pattern-builder
Introduction
- A RegExp builder library that can be used without dependencies.
- Literal text, raw regular expression syntax, and reusable patterns can be composed with a fluent API.
Table of Contents
Installation
npm install @imhonglu/pattern-builder
Usage
Here's an example of creating a userinfo pattern from the URI specification.
For detailed usage, please refer to the API Reference.
// constants.ts
import { alpha, digit, hexDigit, pattern } from "@imhonglu/pattern-builder";
// pct-encoded = "%" HEXDIG HEXDIG
export const pctEncoded = pattern("%", hexDigit.exact(2));
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
export const unreserved = pattern.characterSet(alpha, digit, pattern.raw("\\-._~"));
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
export const subDelims = pattern.raw("[!__CODE_BLOCK_1__amp;'()*+,;=]");
// userinfo.ts
import { pattern } from "@imhonglu/pattern-builder";
import { pctEncoded, subDelims, unreserved } from "./constants.js";
const userinfo = pattern(pctEncoded)
.or(pattern.characterSet(unreserved, subDelims, ":"))
.nonCapturingGroup()
.oneOrMore()
.anchor()
.compile();
console.log(userinfo.test("user:pass")); // true
console.log(userinfo.test("@")); // false
console.log(userinfo.test("@:@")); // false
API Reference
- Package API
- pattern - Compose literal and raw patterns
- PatternBuilder - Build and compile patterns
- RegexNode - Base class for pattern AST nodes