Graphmatch

1.1.1 · active · verified Sun Apr 19

Graphmatch is a low-level utility designed for matching a string against a directed acyclic graph (DAG) composed of regular expressions. It provides flexible matching capabilities, supporting both full and partial string matches against these complex regex structures. Developers can exercise fine-grained control over partial matching behavior at the individual node level within the graph. A key feature is the ability to compile the entire graph into a single JavaScript RegExp object, which significantly optimizes performance for scenarios requiring multiple matches against the same graph. The package is currently at version 1.1.1 and appears to be actively maintained, though no specific release cadence is outlined in the documentation. Its core differentiation lies in offering a programmatic, graph-based approach to regex matching, which is more powerful and manageable than composing single, overly complex regular expressions or chaining multiple simple ones, particularly useful for structured pattern recognition like advanced globbing.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic full and partial string matching against a regex graph, and the compilation of a graph to a single RegExp for performance.

import graphmatch from 'graphmatch';

const GRAPH = {
  regex: /foo/,
  children: [
    {
      regex: /\//,
      children: [
        {
          regex: /bar/,
          children: [
            {
              regex: /\//,
              children: [
                {
                  regex: /qux/
                }
              ]
            }
          ]
        },
        {
          regex: /baz/,
          children: [
            {
              regex: /\//,
              children: [
                {
                  regex: /qux/
                }
              ]
            }
          ]
        }
      ]
    }
  ]
};

// Match against the graph fully
console.log('Full match `foo/bar/qux`:', graphmatch(GRAPH, 'foo/bar/qux')); // => true
console.log('Full match `foo/baz`:', graphmatch(GRAPH, 'foo/baz'));     // => false

// Match against the graph partially
console.log('Partial match `foo/bar/`:', graphmatch(GRAPH, 'foo/bar/', { partial: true })); // => true
console.log('Partial match `bar`:', graphmatch(GRAPH, 'bar', { partial: true }));         // => false

// Compile the graph to a single regex for repeated, efficient matching
const fullCompiledRe = graphmatch.compile(GRAPH);
console.log('Compiled regex test `foo/bar/qux`:', fullCompiledRe.test('foo/bar/qux')); // => true
console.log('Compiled regex test `foo/bar`:', fullCompiledRe.test('foo/bar'));       // => false

const partialCompiledRe = graphmatch.compile(GRAPH, { partial: true });
console.log('Compiled partial regex test `foo/bar`:', partialCompiledRe.test('foo/bar')); // => true

view raw JSON →