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.
npm install -D typed-re
import {match} from "typed-re";
const dateRe = "(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\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
import {match} from "typed-re";
const mailRe = "^(?<username>[a-zA-Z0-9._%+-]+)@(?<domain>[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
Try the code above in the TypeScript playground:
Name | Type | Description |
---|---|---|
s | string | String to parse |
regexp | string | Regular expression as string |
flags | string [optional] | Optional 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.
Copyright 2024 Edwin Martin and released under the MIT license.