1.0.5 • Published 10 months ago
@imhonglu/pattern-builder v1.0.5
@imhonglu/pattern-builder
Introduction
- A RegExp builder library that can be used without dependencies.
- All patterns are converted to regular expressions through the
toRegExpmethod.
Table of Contents
Installation
npm install @imhonglu/pattern-builderUsage
Here's an example of creating a userinfo pattern from URI Spec.
For detailed usage, please refer to the API Reference.
// constants.ts
import { characterSet, concat, hexDigit } from "@imhonglu/pattern-builder";
// pct-encoded = "%" HEXDIG HEXDIG
export const pctEncoded = concat(
"%",
hexDigit.clone().exact(2),
);
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
export const unreserved = characterSet(
alpha,
digit,
/[\-._~]/,
);
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
export const subDelims = characterSet(/[!$&'()*+,;=]/);// userinfo.ts
import { oneOf, characterSet } from "@imhonglu/pattern-builder";
import { pctEncoded, subDelims, unreserved } from "./constants.js";
const pattern = oneOf(pctEncoded, characterSet(unreserved, subDelims, ":"))
.nonCapturingGroup()
.oneOrMore()
.anchor()
.toRegExp();
console.log(pattern.test("user:pass")); // true
console.log(pattern.test("@")); // false
console.log(pattern.test("@:@")); // falseAPI Reference
Pattern Functions
- characterSet - Create character set
- concat - Concatenate strings
- oneOf - Select one of multiple patterns
Pre-defined Patterns
Pattern Builder Classes
- PatternBuilder - Base Builder class
- Characters - Builder class for creating character sets