l1hoeq
Last Updated: February 25, 2016
·
577
· ique
A06d0fc5d5b9a1d254e566c1d0e449a8

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"
Say Thanks
Respond