on 712ffa3 help sign in
77 lines 2.6 kB history raw
1--------------------------------------------------------------------------------
2-- | Miscellaneous string manipulation functions.
3module Hakyll.Core.Util.String
4 ( trim
5 , replaceAll
6 , splitAll
7 , needlePrefix
8 ) where
11--------------------------------------------------------------------------------
12import Data.Char (isSpace)
13import Data.List (isPrefixOf)
14import Data.Maybe (listToMaybe)
15import Text.Regex.TDFA ((=~~))
18--------------------------------------------------------------------------------
19-- | Trim a string (drop spaces, tabs and newlines at both sides).
20trim :: String -> String
21trim = reverse . trim' . reverse . trim'
22 where
23 trim' = dropWhile isSpace
26--------------------------------------------------------------------------------
27-- | A simple (but inefficient) regex replace funcion
28replaceAll :: String -- ^ Pattern
29 -> (String -> String) -- ^ Replacement (called on capture)
30 -> String -- ^ Source string
31 -> String -- ^ Result
32replaceAll pattern f source = replaceAll' source
33 where
34 replaceAll' src = case listToMaybe (src =~~ pattern) of
35 Nothing -> src
36 Just (o, l) ->
37 let (before, tmp) = splitAt o src
38 (capture, after) = splitAt l tmp
39 in before ++ f capture ++ replaceAll' after
42--------------------------------------------------------------------------------
43-- | A simple regex split function. The resulting list will contain no empty
44-- strings.
45splitAll :: String -- ^ Pattern
46 -> String -- ^ String to split
47 -> [String] -- ^ Result
48splitAll pattern = filter (not . null) . splitAll'
49 where
50 splitAll' src = case listToMaybe (src =~~ pattern) of
51 Nothing -> [src]
52 Just (o, l) ->
53 let (before, tmp) = splitAt o src
54 in before : splitAll' (drop l tmp)
58--------------------------------------------------------------------------------
59-- | Find the first instance of needle (must be non-empty) in haystack. We
60-- return the prefix of haystack before needle is matched.
61--
62-- Examples:
63--
64-- > needlePrefix "cd" "abcde" = "ab"
65--
66-- > needlePrefix "ab" "abc" = ""
67--
68-- > needlePrefix "ab" "xxab" = "xx"
69--
70-- > needlePrefix "a" "xx" = "xx"
71needlePrefix :: String -> String -> Maybe String
72needlePrefix needle haystack = go [] haystack
73 where
74 go _ [] = Nothing
75 go acc xss@(x:xs)
76 | needle `isPrefixOf` xss = Just $ reverse acc
77 | otherwise = go (x : acc) xs