Last Updated: February 25, 2016
· ique

Ruby gsub with Haskell

At one point I needed to run a regex replacement on a string in Haskell and found that Text.Regex was quite easy to use for this purpose. This is supposed to have the same behavior as gsub has in Ruby, which is my inspiration for the function. The following code is a Haskell implementation of said gsub.

The import comes from the package regex-compat and I am using the posix backend, regex-posix.

import Text.Regex (mkRegex, matchRegexAll, Regex)

-- | Behaves like Ruby gsub implementation
gsub :: String -> String -> String -> String
gsub regex str replace =
  case matchRegexAll (mkRegex regex) str of
    Nothing -> str
    Just (before, matched, after, _) ->
      before ++ replace ++ (gsub regex after replace)

An example usage:

*Main> gsub "xy|[0-9]" "lets xy 1 3" "go"
"lets go go go"