on 5cc710d help sign in
48 lines 1.5 kB history raw
1-- | Miscellaneous string manipulation functions.
2--
3module Hakyll.Core.Util.String
4 ( trim
5 , replaceAll
6 , splitAll
7 ) where
9import Data.Char (isSpace)
10import Data.Maybe (listToMaybe)
12import Text.Regex.PCRE ((=~~))
14-- | Trim a string (drop spaces, tabs and newlines at both sides).
15--
16trim :: String -> String
17trim = reverse . trim' . reverse . trim'
18 where
19 trim' = dropWhile isSpace
21-- | A simple (but inefficient) regex replace funcion
22--
23replaceAll :: String -- ^ Pattern
24 -> (String -> String) -- ^ Replacement (called on capture)
25 -> String -- ^ Source string
26 -> String -- ^ Result
27replaceAll pattern f source = replaceAll' source
28 where
29 replaceAll' src = case listToMaybe (src =~~ pattern) of
30 Nothing -> src
31 Just (o, l) ->
32 let (before, tmp) = splitAt o src
33 (capture, after) = splitAt l tmp
34 in before ++ f capture ++ replaceAll' after
36-- | A simple regex split function. The resulting list will contain no empty
37-- strings.
38--
39splitAll :: String -- ^ Pattern
40 -> String -- ^ String to split
41 -> [String] -- ^ Result
42splitAll pattern = filter (not . null) . splitAll'
43 where
44 splitAll' src = case listToMaybe (src =~~ pattern) of
45 Nothing -> [src]
46 Just (o, l) ->
47 let (before, tmp) = splitAt o src
48 in before : splitAll' (drop l tmp)