Skip to content

Instantly share code, notes, and snippets.

@roman
Created June 14, 2011 01:36
Show Gist options
  • Save roman/1024144 to your computer and use it in GitHub Desktop.
Save roman/1024144 to your computer and use it in GitHub Desktop.
Nahive implementation of a gsub
module Text.Regex.Gsub
(gsub) where
import Text.Regex.Posix ((=~), MatchText)
import Data.Array ((!))
import Data.Char (isDigit)
-------------------------------------------------------------------------------
gsub :: String -> String -> String -> String
gsub text match replacement = replaceMatches 0 matches text
where
matches =
(text =~ match :: [MatchText String])
rl = length replacement
replaceMatches _ [] text = text
replaceMatches accum (m:ms) text = replaceMatches accum' ms text'
where
(o, l) = snd (m ! 0)
(pre, post) = splitAt (o + accum) text
accum' = accum + (rl - l)
post' = drop l post
text' = pre ++ replacePlaceholder (fst $ m ! 0) match replacement ++ post'
replacePlaceholder :: String -> String -> String -> String
replacePlaceholder expr pattern sub = concat $ zipWith f ('_':sub) sub
where
matches = (expr =~ pattern :: [MatchText String]) !! 0
f :: Char -> Char -> String
f _ '\\' = []
f '\\' i
| isDigit i = fst $ matches ! read [i]
| otherwise = '\\':[i]
f _ x = [x]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment