Skip to content

Template literal types for regular expression capturing groups

License

Notifications You must be signed in to change notification settings

edwinm/typed-re

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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])

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.

License

Copyright 2024 Edwin Martin and released under the MIT license.

About

Template literal types for regular expression capturing groups

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published