regex-fun: Functional Regular Expression Builder

3.1.0 · active · verified Wed Apr 22

regex-fun is a utility library for JavaScript and TypeScript that facilitates the programmatic construction of regular expressions using a functional, composable API. It provides a comprehensive set of functions like `combine`, `either`, `capture`, and various quantifiers (e.g., `optional`, `anyNumber`, `oneOrMore`, `exactly`, `atLeast`, `between`, and their non-greedy counterparts) to build complex regex patterns from smaller, readable components. A key differentiator is its automatic escaping of string inputs, which prevents common regex syntax errors when embedding literal strings, treating them as fixed text rather than regex patterns. The library ships with TypeScript types, ensuring strong type-checking and autocompletion for users in modern development environments. The current stable version is 3.1.0, and new functions are added on an ad-hoc basis driven by maintainer needs, rather than a strict release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates building a complex regular expression using `either`, `optional`, `combine`, and `capture` to parse a greeting followed by a word. It also shows the automatic string escaping feature.

import { combine, optional, capture, either } from 'regex-fun';

const anyGreeting = either('howdy', 'hi', 'hey');
// The comma is optional, followed by a space, then a captured word.
const regex = combine(anyGreeting, optional(','), ' ', capture(/\w+/));

console.log(regex); // => /(?:howdy|hi|hey)(?:,)? (\w+)/

const matchResult = 'hey bub'.match(regex);
if (matchResult && matchResult[1]) {
  console.log(matchResult[1]); // => 'bub'
} else {
  console.log('No match found.');
}

// Example of automatic string escaping:
const escapedRegex = combine('a+');
console.log(escapedRegex); // => /a\+/
// This will match 'a+' literally, not one or more 'a's.
console.log('a+'.match(escapedRegex)); // => ['a+', index: 0, input: 'a+', groups: undefined]

view raw JSON →