module Text.Hakyll.Regex
( splitRegex
, substituteRegex
, matchesRegex
) where
import Text.Regex.TDFA
matchRegexAll :: Regex -> String -> Maybe (String, String, String, [String])
matchRegexAll = matchM
subRegex :: Regex
-> String
-> String
-> String
subRegex _ "" _ = ""
subRegex regexp inp replacement =
let
bre = makeRegex "\\\\(\\\\|[0-9]+)"
lookup' _ [] _ = []
lookup' [] _ _ = []
lookup' match' repl groups =
case matchRegexAll bre repl of
Nothing -> repl
Just (lead, _, trail, bgroups) ->
let newval =
if head bgroups == "\\"
then "\\"
else let index :: Int
index = read (head bgroups) 1
in if index == 1
then match'
else groups !! index
in lead ++ newval ++ lookup' match' trail groups
in case matchRegexAll regexp inp of
Nothing -> inp
Just (lead, match', trail, groups) ->
lead ++ lookup' match' replacement groups
++ subRegex regexp trail replacement
splitRegex' :: Regex -> String -> [String]
splitRegex' _ [] = []
splitRegex' delim strIn = loop strIn where
loop str = case matchOnceText delim str of
Nothing -> [str]
Just (firstline, _, remainder) ->
if null remainder
then [firstline,""]
else firstline : loop remainder
splitRegex :: String -> String -> [String]
splitRegex pattern = filter (not . null)
. splitRegex' (makeRegex pattern)
substituteRegex :: String
-> String
-> String
-> String
substituteRegex pattern replacement string =
subRegex (makeRegex pattern) string replacement
matchesRegex :: String
-> String
-> Bool
matchesRegex = (=~)