Skip to content

A typescript library for type-safe regex for named capture groups, deno fork

License

Notifications You must be signed in to change notification settings

scarf005/typed_regex

 
 

Repository files navigation

typed_regex

deno module Tests

type-safe regular expression parser for named capture groups.

Features

Usage

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

import { typedRegEx } from "https://deno.land/x/typed_regex@$MODULE_VERSION/mod.ts"
import { assertType, IsExact } from "https://deno.land/[email protected]/testing/types.ts"

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

assertType<IsExact<typeof result, Result>>(true)

type 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@$MODULE_VERSION/mod.ts"
import { assertType, IsExact } from "https://deno.land/[email protected]/testing/types.ts"

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

assertType<IsExact<typeof result, Result>>(true)

type 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

import { typedRegEx } from "https://deno.land/x/typed_regex@$MODULE_VERSION/mod.ts"
import { assertType, IsExact } from "https://deno.land/[email protected]/testing/types.ts"

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

assertType<IsExact<typeof result, Result>>(true)

type 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

Contributing

  1. for large changes, please open issues before opening PRs.
  2. please verify the changes with:
$ deno fmt
$ deno lint
$ deno test --doc

About

A typescript library for type-safe regex for named capture groups, deno fork

Resources

License

Stars

Watchers

Forks

Languages

  • TypeScript 100.0%