Is there a high-level API for doing search-and-replace with regexes in Haskell? In particular, I\'m looking at the Text.Regex.TDFA
or Text.Regex.Posix
I don't know of any existing function that creates this functionality, but I think that I'd end up using something like the AllMatches [] (MatchOffset, MatchLength) instance of RegexContent to simulate it:
replaceAll :: RegexLike r String => r -> (String -> String) -> String -> String
replaceAll re f s = start end
where (_, end, start) = foldl' go (0, s, id) $ getAllMatches $ match re s
go (ind,read,write) (off,len) =
let (skip, start) = splitAt (off - ind) read
(matched, remaining) = splitAt len matched
in (off + len, remaining, write . (skip++) . (f matched ++))
replaceAllM :: (Monad m, RegexLike r String) => r -> (String -> m String) -> String -> m String
replaceAllM re f s = do
let go (ind,read,write) (off,len) = do
let (skip, start) = splitAt (off - ind) read
let (matched, remaining) = splitAt len matched
replacement <- f matched
return (off + len, remaining, write . (skip++) . (replacement++))
(_, end, start) <- foldM go (0, s, return) $ getAllMatches $ match re s
start end