How do I only replace the first occurrence of a "substring" (actually Data.Text.Text) in a Text value in Haskell in the most efficient way?
You can breakOn
the substring,
breakOn :: Text -> Text -> (Text, Text)
to split the Text
into two parts at the first occurrence of the pattern, then replace the substring at the start of the second component:
replaceOne :: Text -> Text -> Text -> Text
replaceOne pattern substitution text
| T.null back = text -- pattern doesn't occur
| otherwise = T.concat [front, substitution, T.drop (T.length pattern) back]
where
(front, back) = breakOn pattern text
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With