Created
June 14, 2011 01:36
-
-
Save roman/1024144 to your computer and use it in GitHub Desktop.
Nahive implementation of a gsub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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