Suppose I have a string s and a list of tuples of strings ts, where the first element in the tuple is the substring of s I'd like to replace with the corresponding second element. In my case, the string s will always be a space-separated list of distinct words; moreover, I wish to replace each word in s in its entirety with the corresponding value in ts (I hope my intent is clear here). A first attempt at this might be:
import qualified Text.Regex as R -- from regex-compat
replaceAllIn :: String -> [(String, String)] -> String
replaceAllIn = foldl (\acc (k, v) -> R.subRegex (R.makeRegex k) acc v)
This, of course, doesn't work when one key is a substring of another
λ> s = "blah blahblee"
λ> ts = [("blah", "asdf"), ("blahblee", ";lkj")]
λ> replaceAllIn s ts
"asdf asdfblee"
because the first key replaces both occurrences of "blah" upon the first pass, leaving a string that no longer has anything matching "blahblee" for the second pass.
Is there a way to achieve what I want in one pass through the string? Or is there a built-in way (in some library somewhere) to replace multiple patterns at once?
Edit: Immediately after posting I realized I don't know why I'm using regex here. But the question remains valid if I replaced regex substitution with something like replace from MissingH's Data.String.Utils.
"foobar"with"marmoset"and"barbaz"with"elephant"when the string contains"foobarbaz"?tsto replace the longest strings first?\acc,. Otherwise, nice Haskell regex code.