Skip to content

A typescript library for type-safe regex for named capture groups

License

Notifications You must be signed in to change notification settings

phenax/typed-regex

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

typed-regex

A typescript library for writing type-safe regular expressions using named capture groups.

GitHub Workflow Status (main) npm npm bundle size

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 browsers

License

Typed-Regex is licensed under MIT