An open API service indexing awesome lists of open source software.

https://github.com/phenax/typed-regex

A typescript library for type-safe regex for named capture groups
https://github.com/phenax/typed-regex

capture-group regex regular-expression typescript

Last synced: 6 months ago
JSON representation

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

Awesome Lists containing this project

README

        

# typed-regex
A typescript library for writing type-safe regular expressions using [named capture groups](https://github.com/tc39/proposal-regexp-named-groups).

![GitHub Workflow Status (main)](https://img.shields.io/github/workflow/status/phenax/typed-regex/Node.js%20CI/main)
[![npm](https://img.shields.io/npm/v/typed-regex)](https://www.npmjs.com/package/typed-regex)
[![npm bundle size](https://img.shields.io/bundlephobia/minzip/typed-regex)](https://www.npmjs.com/package/typed-regex)

## 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.

```ts
import { TypedRegEx } from 'typed-regex';

const regex = TypedRegEx('^(?\\d{4})-(?\\d{2})-(?\\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

```ts
const regex = TypedRegEx('(?\\d+)/(?\\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](https://github.com/phenax/typed-regex/blob/main/docs/API.md)

## Browser support
Named capture groups are supported in [these browsers](https://caniuse.com/mdn-javascript_builtins_regexp_named_capture_groups)

## License
Typed-Regex is licensed under [MIT](./LICENSE)