Type-safe regular expression pattern builder for TypeScript with fluent API
npm install @imhonglu/pattern-builder- A RegExp builder library that can be used without dependencies.
- All patterns are converted to regular expressions through the toRegExp method.
- Installation
- Usage
- API Reference
``bash`
npm install @imhonglu/pattern-builder
Here's an example of creating a userinfo pattern from URI Spec.
For detailed usage, please refer to the API Reference.
`ts
// 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(/[!$&'()*+,;=]/);
`
`ts
// 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("@:@")); // false
`
- characterSet - Create character set
- concat - Concatenate strings
- oneOf - Select one of multiple patterns
- alpha - /[a-zA-Z]//[\d]/
- digit - /[\da-fA-F]/`
- hexDigit -
- PatternBuilder - Base Builder class
- Characters - Builder class for creating character sets