on fb71a21 help sign in
hakyll/src/Text/Hakyll/Regex.hs
66 lines 2.7 kB history raw
1-- | A module that exports a simple regex interface. This code is mostly copied
2-- from the regex-compat package at hackage.
3module Text.Hakyll.Regex
4 ( split
5 , substitute
6 ) where
8import Text.Regex.TDFA
10-- | Match a regular expression against a string, returning more information
11-- about the match.
12matchRegexAll :: Regex -> String -> Maybe (String, String, String, [String])
13matchRegexAll p str = matchM p str
15-- | Replaces every occurance of the given regexp with the replacement string.
16subRegex :: Regex -- ^ Search pattern
17 -> String -- ^ Input string
18 -> String -- ^ Replacement text
19 -> String -- ^ Output string
20subRegex _ "" _ = ""
21subRegex regexp inp replacement =
22 let -- bre matches a backslash then capture either a backslash or some digits
23 bre = makeRegex "\\\\(\\\\|[0-9]+)"
24 lookup' _ [] _ = []
25 lookup' [] _ _ = []
26 lookup' match' repl groups =
27 case matchRegexAll bre repl of
28 Nothing -> repl
29 Just (lead, _, trail, bgroups) ->
30 let newval =
31 if (head bgroups) == "\\"
32 then "\\"
33 else let index :: Int
34 index = (read (head bgroups)) - 1
35 in if index == -1
36 then match'
37 else groups !! index
38 in lead ++ newval ++ lookup' match' trail groups
39 in case matchRegexAll regexp inp of
40 Nothing -> inp
41 Just (lead, match', trail, groups) ->
42 lead ++ lookup' match' replacement groups ++ (subRegex regexp trail replacement)
44-- | Splits a string based on a regular expression. The regular expression
45-- should identify one delimiter.
46splitRegex :: Regex -> String -> [String]
47splitRegex _ [] = []
48splitRegex delim strIn = loop strIn where
49 loop str = case matchOnceText delim str of
50 Nothing -> [str]
51 Just (firstline, _, remainder) ->
52 if null remainder
53 then [firstline,""]
54 else firstline : loop remainder
56-- | Split a list at a certain element.
57split :: String -> String -> [String]
58split pattern = filter (not . null)
59 . splitRegex (makeRegex pattern)
61-- | Substitute a regex. Simplified interface.
62substitute :: String -- ^ Pattern to replace (regex).
63 -> String -- ^ Replacement string.
64 -> String -- ^ Input string.
65 -> String -- ^ Result.
66substitute pattern replacement str = subRegex (makeRegex pattern) str replacement