https://github.com/edwinm/typed-re
Template literal types for regular expression capturing groups
https://github.com/edwinm/typed-re
capturing-groups regular-expression template-literal-types
Last synced: 6 months ago
JSON representation
Template literal types for regular expression capturing groups
- Host: GitHub
- URL: https://github.com/edwinm/typed-re
- Owner: edwinm
- License: mit
- Created: 2024-10-03T19:35:01.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2025-09-15T18:18:46.000Z (10 months ago)
- Last Synced: 2025-09-15T20:23:51.532Z (10 months ago)
- Topics: capturing-groups, regular-expression, template-literal-types
- Language: TypeScript
- Homepage:
- Size: 208 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# typed-re
> Template literal types for regular expression capturing groups
When using a regular expression to parse a string, use capturing groups and the resulting
`groups` property will be correctly typed.
## Install
```bash
npm install -D typed-re
```
## Date example
```typescript
import {match} from "typed-re";
const dateRe = "(?\\d{4})-(?\\d{2})-(?\\d{2})";
const dateMatch = match(dateRe, "2024-10-28");
console.log(dateMatch?.groups.day); // OK, will be 28
// console.log(dateMatch?.groups.hour); TYPE ERROR
```

## Email example
```typescript
import {match} from "typed-re";
const mailRe = "^(?[a-zA-Z0-9._%+-]+)@(?[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,})$"
const mailMatch = match(mailRe, "mark@example.com");
console.log(mailMatch?.groups.username); // OK, will be mark
// console.log(mailMatch?.groups.host); TYPE ERROR
```
## Playground
Try the code above in the TypeScript playground:
[](https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbxAQxgYwBYF84DMoQhwBEMAnmAKYAmAtFJcQNwBQLA9J13ACKqVxKAD2TgANgK5c2aCADsAzvGr8ASgIC8JABQB+ADxlKyKAD4AOueoIALFgCUtPfpDyYGC1YQAmB04MqZJ7WvvbMMvJKcCowlACyqJhwWijoGNrE3gAM3ja0AIxZtN4AHMQANNFqlPasEYoQEgB0YhAA5tox8YkYuk1tBACuYApNgbVwnHAA8gDSbFOyDc2tHV0JaX0DEMOjGDtQEwCiqqrTqmyXUlNHKMBigiLiktf1UXdi6skkAHrOgwpKFA5KJKKYANrIWgALwAgrQAFpFACcTQA+gBSADUtAAulj7AABZzUQjIYByCFQuGIlFNPFYyxNSEw+EI3E+coOAAkxDe8A+GySKR6GRQUAA1oThKIwM1ZCAKnAPupam9GpQWu1tIKelshiMmgCgSCQDUmJN2DN5hwrUsFBqtR1dZt+ga9hAlMdTucgA)
## Usage
### `match(s, regexp [, flags])`
| Name | Type | Description |
|--------|-------------------|------------------------------|
| s | string | String to parse |
| regexp | string | Regular expression as string |
| flags | string [optional] | Optional [flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions#advanced_searching_with_flags) |
Returns the same regex result object as `String.prototype.match()` or `RegExp.prototype.exec()`.
> [!NOTE]
> The regular expression should be a string, not a regular expression literal.
## License
Copyright 2024 [Edwin Martin](https://bitstorm.org/) and released under the MIT license.