Skip to content

Regular Expression Matching

Conan edited this page Apr 26, 2022 · 5 revisions

match-iz 🔥 docs

Regular Expression Matching

Default behaviour

import { match, when } from 'match-iz'

match('hello, world!')(
  when(/world/, fullRegExpMatchArray => {
    return fullRegExpMatchArray
  })
)
// [ 'world', index: 7, input: 'hello, world!', groups: undefined ]

match({ text: 'hello, world!' })(
  when({ text: /world/ }, haystack => {
    return haystack
  })
)
// { text: 'hello, world!' }
  1. Passing a RegExp literal to when will pass the match-array as the first argument to handler (if it's a function).

  2. Using a RegExp on an object-prop passes the value from match(), as usual.

Named capture-groups

If specified, capture groups are extracted automatically from regular-expressions (with the second argument of the when-handler being the full-match if you need it):

import { match, when, otherwise } from 'match-iz'

match('1 + 2')(
  when(
    /(?<left>\d+) \+ (?<right>\d+)/,
    ({ left, right }, fullRegExpMatchArray) => {
      return add(left, right)
    }
  ),

  when(/no capture groups/, fullRegExpMatchArray => {
    return 'so we get the full match array only'
  }),

  otherwise("I couldn't parse that!")
)
// 3