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