@algosail/regexp
v0.1.0
Published
Small collection of FP utilities for working with regular expressions.
Readme
@algosail/regexp
RegExp comparison and utility functions. All operations are stateless — lastIndex is always restored.
Contents
equals
equals :: RegExp -> RegExp -> BooleanTrue when both regexes have the same source and all flags match (g, i, m, s, y, u).
equals(/a/g)(/a/g) // => true
equals(/a/g)(/a/) // => false (flags differ)
equals(/a/)(/b/) // => false (source differs)regex
regex :: String -> String -> RegExpConstructs a RegExp from a flags string and a source string.
regex('')('hello') // => /hello/
regex('gi')('[a-z]+') // => /[a-z]+/giregexEscape
regexEscape :: String -> StringEscapes all regex metacharacters so the string can be used as a literal pattern.
regexEscape('a.b') // => 'a\\.b'
regexEscape('1+1=2') // => '1\\+1=2'
regexEscape('$100') // => '\\$100'
// Typical use: build a dynamic regex from user input
const term = regexEscape(userInput)
const pattern = new RegExp(term, 'i')test
test :: RegExp -> String -> BooleanTests whether the pattern matches the string. Safe to call with sticky/global patterns — lastIndex is always reset.
test(/^hello/)('hello world') // => true
test(/^hello/)('world') // => false
// Safe with global/sticky flags
const re = /\d+/g
test(re)('abc123') // => true
test(re)('abc123') // => true (lastIndex was reset)match
match :: RegExp -> String -> Maybe (Array (Maybe String))Returns Just of the capture-group array if the pattern matches, Nothing otherwise. Each capture group is itself a Maybe — Nothing for unmatched optional groups.
match(/(\w+)\s(\w+)/)('hello world')
// => just([just('hello'), just('world')])
match(/(\w+)?/)('')
// => just([nothing()]) — group didn't participate
match(/\d+/)('abc')
// => nothing()
// Destructure groups:
const result = match(/(\d{4})-(\d{2})-(\d{2})/)('2024-01-15')
// => just([just('2024'), just('01'), just('15')])matchAll
matchAll :: RegExp -> String -> Array (Array (Maybe String))Returns all capture-group arrays for every match. The pattern must have the g flag.
matchAll(/(\w+)/g)('hi there')
// => [[just('hi')], [just('there')]]
matchAll(/(\d+)-(\d+)/g)('1-2 and 3-4')
// => [[just('1'), just('2')], [just('3'), just('4')]]
matchAll(/x/g)('abc')
// => []replace
replace :: (Array (Maybe String) -> String) -> RegExp -> String -> StringReplaces pattern matches using a function over the capture groups. The substitute function receives the same Maybe-wrapped groups as match.
replace(() => 'X')(/a/)('cat')
// => 'cXt'
// Swap day and month in a date string
replace(([day, month]) => `${fromMaybe('')(month)}-${fromMaybe('')(day)}`)(
/(\d{2})\/(\d{2})/,
)('15/01')
// => '01-15'
// Upper-case every word
replace(([w]) => fromMaybe('')(map((s) => s.toUpperCase())(w)))(/(\w+)/g)(
'hello world',
)
// => 'HELLO WORLD'