Skip to content

unifiers matchString()

Eugene Lazutkin edited this page Apr 6, 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 value to unify with the full match result array. Typically a Variable or an array pattern.
  • props — an optional value to unify with the match properties object ({index, input}). Typically a Variable or an object pattern.

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.

Examples

Capture groups with variables:

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

// Capture email parts using regex groups
const matches = variable('matches');
const env = unify('user@example.com', matchString(/^(.+)@(.+)$/, matches));
// matches.get(env) === ['user@example.com', 'user', 'example.com']

// Capture specific groups into individual variables
const user = variable('user');
const domain = variable('domain');
const env2 = unify('user@example.com', matchString(/^(.+)@(.+)$/, [any, user, domain]));
// user.get(env2) === 'user'
// domain.get(env2) === 'example.com'

Capture match properties:

const props = variable('props');
const env3 = unify('hello world', matchString(/world/, null, props));
// props.get(env3) === {index: 6, input: 'hello world'}

Clone this wiki locally