1.1.0 • Published 10 months ago

typed-re v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

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

npm install -D typed-re

Date example

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

typed-re date example

Email example

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

Playground

Try the code above in the TypeScript playground:

typed-re date example

Usage

match(s, regexp [, flags])

NameTypeDescription
sstringString to parse
regexpstringRegular expression as string
flagsstring optionalOptional 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 and released under the MIT license.