replacement / substition with Haskell regex libraries

前端 未结 6 459
无人共我
无人共我 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:56

    maybe this approach fit you.

    import Data.Array (elems)
    import Text.Regex.TDFA ((=~), MatchArray)
    
    replaceAll :: String -> String -> String -> String        
    replaceAll regex new_str str  = 
        let parts = concat $ map elems $ (str  =~  regex :: [MatchArray])
        in foldl (replace' new_str) str (reverse parts) 
    
      where
         replace' :: [a] -> [a] -> (Int, Int) -> [a]
         replace' new list (shift, l)   = 
            let (pre, post) = splitAt shift list
            in pre ++ new ++ (drop l post)
    

提交回复
热议问题