Skip to content

callstack/ts-regex-builder

Repository files navigation

TS Regex Builder

User-friendly Regular Expression builder for TypeScript and JavaScript.

Goal

Regular expressions are a powerful tool for matching complex text patterns, yet they are notorious for their hard-to-understand syntax.

Inspired by Swift's Regex Builder, this library allows users to write easily and understand regular expressions.

// Before
const hexColor = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;

// After
const hexDigit = characterClass(
  characterRange('a', 'f'),
  characterRange('A', 'F'),
  characterRange('0', '9')
);

const hexColor = buildRegex(
  startOfString,
  optionally('#'),
  capture(
    choiceOf(repeat({ count: 6 }, hexDigit), repeat({ count: 3 }, hexDigit))
  ),
  endOfString
);

Installation

npm install ts-regex-builder

Usage

import { buildRegex, capture, oneOrMore } from 'ts-regex-builder';

// /Hello (\w+)/
const regex = buildRegex(['Hello ', capture(oneOrMore(word))]);

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

See the project guidelines to understand our core principles.

License

MIT

Reference


Made with create-react-native-library