1.0.1 • Published 12 months ago

@henry-yslin/ts-regex v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

CI Coverage Status TypeScript npm npm bundle size Dependency Count

Installation

Install ts-regex with your preferred package manager, and then import it with CommonJS or ES Modules syntax:

npm install @henry-yslin/ts-regex

yarn add @henry-yslin/ts-regex
import { regex } from '@henry-yslin/ts-regex';

const { regex } = require('@henry-yslin/ts-regex');

Usage

Simply use the provided regex function to create RegExp objects. You will get strongly-typed match results and compile-time regex syntax check for free!

import { regex } from '@henry-yslin/ts-regex';

const nameRegex = regex('(?<first>[a-zA-Z_$])[a-zA-Z0-9_$]*');

const result = nameRegex.exec('foo');

// @ts-expect-error Property 'second' does not exist on type '{ first: string; }'.
console.log(result?.groups.second);
// @ts-expect-error '\\2' is being parsed as an octal character escape sequence, which is banned because it is easily confused with a back-reference.
const backRefRegex = regex('(.+)\\2');
// @ts-expect-error '\\u134' is not a valid unicode escape sequence and is being parsed literally. Do not escape the 'u' character when not in a unicode escape sequence.
const unicodeRegex = regex('\\u134');
const nameRegex = regex('www\\.(?<name>.+)\\.com');
const result = 'https://www.google.com'.match(nameRegex);

console.log(result?.groups.name); // strongly-typed match result

// @ts-expect-error the named capture group "domain" does not exist
console.log(result?.groups.domain);