Skip to main content

typed_regex

type-safe regular expression parser for named capture groups.

Features

Usage

The type of the result object is infered from the regular expression.

import { typedRegEx } from "https://deno.land/x/typed_regex/mod.ts"

const regex = typedRegEx(
    "^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$",
    "g",
)
const result = regex.captures("2020-12-02")

result //=> { year: string, month: string, day: string } | undefined

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

import { typedRegEx } from "https://deno.land/x/typed_regex@0.1.0/mod.ts"

const regex = typedRegEx("(?<first>\\d+)/(?<second>\\w+)?", "g")
const result = regex.captures("1234/foobar")

result //=> { first: string, second: string | undefined } | undefined

Non Capturing groups

If the capture group is marked as non-capturing in the regular expression, the generated type will ignore it

const r = typedRegEx("^(?:foo)$")
const result = r.captures("foo")

result //=> {} | undefined

Browser support

Most modern browsers support named capture groups. For details, check these browsers

Changes from original library

Breaking Changes

names changed to

  • TypedRegex -> typedRegex (since it’s no longer a class but a function)
  • TypedRegexT -> TypedRegex (since it’s no longer a class but a type)

Internal Changes

  • getRegex() is now a cached variable instead of a method.
  • RegExp is now a closure instead of class.

License

Typed_Regex is licensed under MIT