replacement / substition with Haskell regex libraries

前端 未结 6 460
无人共我
无人共我 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 01:46

    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
    

提交回复
热议问题