I need to make a version of the function subRegex which works with Text.Regex.PCRE.
The version of subRegex provided in the Text.Regex module is this:
{- | Replaces every occurance of the given regexp with the replacement string.
In the replacement string, @\"\\1\"@ refers to the first substring;
@\"\\2\"@ to the second, etc; and @\"\\0\"@ to the entire match.
@\"\\\\\\\\\"@ will insert a literal backslash.
This does not advance if the regex matches an empty string. This
misfeature is here to match the behavior of the the original
Text.Regex API.
-}
subRegex :: Regex -- ^ Search pattern
-> String -- ^ Input string
-> String -- ^ Replacement text
-> String -- ^ Output string
subRegex _ "" _ = ""
subRegex regexp inp repl =
let compile _i str [] = \ _m -> (str++)
compile i str (("\\",(off,len)):rest) =
let i' = off+len
pre = take (off-i) str
str' = drop (i'-i) str
in if null str' then \ _m -> (pre ++) . ('\\':)
else \ m -> (pre ++) . ('\\' :) . compile i' str' rest m
compile i str ((xstr,(off,len)):rest) =
let i' = off+len
pre = take (off-i) str
str' = drop (i'-i) str
x = read xstr
in if null str' then \ m -> (pre++) . ((fst (m!x))++)
else \ m -> (pre++) . ((fst (m!x))++) . compile i' str' rest m
compiled :: MatchText String -> String -> String
compiled = compile 0 repl findrefs where
-- bre matches a backslash then capture either a backslash or some digits
bre = mkRegex "\\\\(\\\\|[0-9]+)"
findrefs = map (\m -> (fst (m!1),snd (m!0))) (matchAllText bre repl)
go _i str [] = str
go i str (m:ms) =
let (_,(off,len)) = m!0
i' = off+len
pre = take (off-i) str
str' = drop (i'-i) str
in if null str' then pre ++ (compiled m "")
else pre ++ (compiled m (go i' str' ms))
in go 0 inp (matchAllText regexp inp)
When I run this with Text.Regex.PCRE imported, I get
Not in scope: ‘mkRegex’
There is a function called makeRegex in the RegexLike module but it has a different type and this is where I’m stuck.
Edit – Solution
Create new mkRegex function like so:
-- | Makes a regular expression with the default options
mkRegex :: String -> Regex
mkRegex s = makeRegexOpts opt defaultExecOpt s
where opt = (defaultCompOpt + compCaseless) -- or other options
mkRegexis defined inText.Regexin the regex-compat package. You could try just copying its source. I’d be surprised if it worked completely without change, but perhaps not too much is necessary.