typed-regex
v0.0.8
Published
A typescript library for writing type-safe regular expressions using named capture groups
Downloads
5,097
Readme
typed-regex
A typescript library for writing type-safe regular expressions using named capture groups.
Install
To install the latest stable version of typed-regex -
yarn add typed-regex
// OR
npm install --save typed-regex
Usage
The type of the result object is infered from the regular expression.
import { TypedRegEx } from 'typed-regex';
const regex = TypedRegEx('^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$', 'g');
const result = regex.captures('2020-12-02');
result // : undefined | { year: string, month: string, day: string }
NOTE: The regular expression has to be a string literal for the types to be valid
Optional properties
If the capture group is marked as optional in the regular expression, the generated type will reflect that
const regex = TypedRegEx('(?<first>\\d+)/(?<second>\\w+)?', 'g');
const result = regex.captures('1234/foobar');
result // : undefined | { first: string, second?: string }
API Docs
You can find more information about the library in the API documentation
Browser support
Named capture groups are supported in these browser
License
Typed-Regex is licensed under MIT