Skip to content

unifiers matchString()

Eugene Lazutkin edited this page Apr 3, 2026 · 5 revisions

Matches strings against regular expressions with optional capture group binding.

Introduction

This unifier matches string values against a regular expression and can capture match groups into variables.

import matchString from 'deep6/unifiers/matchString.js';
import {variable} from 'deep6/env.js';
import unify from 'deep6/unify.js';

const matches = variable('matches');
const env = unify('user@example.com', matchString(/^(.+)@(.+)$/, matches));

// matches.get(env) === ['user@example.com', 'user', 'example.com']

API

matchString(regexp [, matches] [, props])

Arguments:

  • regexp — a required RegExp to match against.
  • matches — an optional variable name or Variable to capture the full match array.
  • props — an optional variable name or Variable to capture match properties (index, input).

Returns a MatchString unifier instance.

Class: MatchString

Extends Unifier. The constructor takes the same arguments as the factory function.

Properties

  • regexp — the RegExp used for matching.
  • matches — the variable for capturing match array.
  • props — the variable for capturing match properties.

Methods

  • unify(val, ls, rs) — attempts to match val against the regex.
    • Returns the match result (truthy) on success.
    • Returns false if val is a Variable or doesn't match.

Example

import matchString from 'deep6/unifiers/matchString.js';
import {variable} from 'deep6/env.js';
import unify from 'deep6/unify.js';

const emailPattern = {
  local: variable('local'),
  domain: variable('domain'),
  full: variable('full')
};

const matcher = {
  local: matchString(/^[^@]+/, emailPattern.local),
  domain: matchString(/@[^@]+$/, emailPattern.domain),
  full: matchString(/^.+@.+$/, emailPattern.full)
};

const env = unify('user@example.com', matcher);
// All variables bound to captured values

Clone this wiki locally