Skip to content

Instantly share code, notes, and snippets.

@ruthenium
Created September 16, 2012 15:57
Show Gist options
  • Save ruthenium/3732949 to your computer and use it in GitHub Desktop.
Save ruthenium/3732949 to your computer and use it in GitHub Desktop.
Haskell subRegex with transformer, similar to gsub in ruby and other languages.
import Text.Regex (mkRegex, matchRegexAll, Regex)
------------------------------------------------------------------------------
{- | Taken from the <http://pleac.sourceforge.net/pleac_haskell/strings.html>
'subRegex' allows only a fixed 'String'
This custom version takes a ('String' -> 'String') function to compute
a result.
The function is applied to the all matched results, which are found
recursively.
-}
subRegexF :: Regex -> (String -> String) -> String -> String
subRegexF regex func str =
case matchRegexAll regex str of
Nothing -> str
Just (before, matched, after, _) ->
before ++ func matched ++ (subRegexF regex func after)
------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment