replacement / substition with Haskell regex libraries

前端 未结 6 462
无人共我
无人共我 2021-02-04 01:20

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

6条回答
  •  执念已碎
    2021-02-04 02:09

    Based on @rampion's answer, but with the typo fixed so it doesn't just <>:

    replaceAll :: Regex -> (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 start 
                in (off + len, remaining, write . (skip++) . (f matched ++))
    

提交回复
热议问题