npm.io
2.0.0 • Published 21h ago

@imhonglu/pattern-builder

Licence
MIT
Version
2.0.0
Deps
0
Size
82 kB
Vulns
0
Weekly
0
Stars
14

@imhonglu/pattern-builder

English | 한국어

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

Pre-defined Patterns

Keywords