Regular Expressions in PureScript

Our first program demonstrates common regular expression operations in PureScript. Here’s the full source code:

module Main where

import Prelude

import Data.Array (filter)
import Data.Maybe (Maybe(..))
import Data.String.Regex (Regex, test, match, replace, regex, parseFlags)
import Data.String.Regex.Flags (global, ignoreCase)
import Data.String.Regex.Unsafe (unsafeRegex)
import Effect (Effect)
import Effect.Console (log)

main :: Effect Unit
main = do
  -- This tests whether a pattern matches a string.
  let matchResult = test (unsafeRegex "p([a-z]+)ch" global) "peach"
  log $ show matchResult

  -- For other regex tasks, we'll use a compiled Regex.
  let r = unsafeRegex "p([a-z]+)ch" global

  -- Here's a match test like we saw earlier.
  log $ show $ test r "peach"

  -- This finds the match for the regex.
  case match r "peach punch" of
    Just matches -> log $ show $ matches
    Nothing -> log "No match found"

  -- The `match` function returns information about both
  -- the whole-pattern matches and the submatches.
  case match r "peach punch" of
    Just matches -> log $ show matches
    Nothing -> log "No match found"

  -- The `match` function with the global flag will find all matches.
  case match (unsafeRegex "p([a-z]+)ch" $ parseFlags "g") "peach punch pinch" of
    Just matches -> log $ show matches
    Nothing -> log "No matches found"

  -- The `replace` function can be used to replace subsets of strings.
  log $ replace r "<fruit>" "a peach"

  -- The `replace` function can also use a function to transform matched text.
  log $ replace r (\_ -> "PEACH") "a peach"

To run the program, save it as RegexExample.purs and use the PureScript compiler and runtime:

$ pulp run
true
true
["peach","ea"]
["peach","ea"]
["peach","ea","punch","un","pinch","in"]
a <fruit>
a PEACH

This example demonstrates basic regex operations in PureScript. The Data.String.Regex module provides functions for working with regular expressions. Note that PureScript’s regex implementation may differ slightly from Go’s, but the core concepts remain the same.

For a complete reference on PureScript regular expressions, check the Data.String.Regex module documentation.