regexhaskellreplace

find and replace with the haskell package Text.RE.TDFA


I'm attempting to replace numbers in a string with twice their value using Haskell's Text.RE.TDFA package. My current approach:

s *=~/ fmap (\x -> show $ 2.0*(read x::Double)) [ed|${doublestring}([0-9]*\.[0-9]*)///${doublestring}|]

Behavior Observed:

  1. When I set s as "xxx1.1xxx", I get the error:
    "regex.hs: Prelude.read: no parse"
  2. If I replace ${doublestring} after /// with a literal number (e.g., 1.1), it works as expected:
    Input: "xxx1.1xxx" → Output: "xxx2.2xxx"

Questions:

  1. Why does the ${doublestring} capture fail during parsing?
  2. What's the proper way to implement the replacement with the TDFA backend?

Solution

  • Since the domain name of documentation website appears to have expired earlier this year, I think the best I can point you to is the source code for the tutorial. Starting at this line, there's documentation for how to apply functions to captured strings. You'll need to use the replaceAllCaptures function, so something like the following should work:

    print $ replaceAllCaptures ALL double $ "xx1.1xx" *=~ [re|[0-9]+\.[0-9]+|]
      where double _ _ cap = show . ((2.0 :: Double) *) <$> readMaybe (capturedText cap)