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
- Host: GitHub
- URL: https://github.com/phenax/typed-regex
- Owner: phenax
- License: mit
- Created: 2021-06-09T17:14:40.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2022-04-16T17:49:58.000Z (about 3 years ago)
- Last Synced: 2024-12-11T06:21:57.259Z (6 months ago)
- Topics: capture-group, regex, regular-expression, typescript
- Language: TypeScript
- Homepage:
- Size: 122 KB
- Stars: 83
- Watchers: 3
- Forks: 4
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
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).
[](https://www.npmjs.com/package/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)