I want to replace "\\" from a bytestring sequence (Data.ByteString) with "\", but due to the internal escaping of "\" it won't work. Consider following example:
The original bytestring:
"\159\DEL*\150\222/\129vr\205\241=mA\192\184"
After storing in and re-reading from a database I obtain following bytestring:
"\"\\159\\DEL*\\150\\222/\\129vr\\205\\241=mA\\192\\184\""
Imagine that the bytestring is used as a cryptographic key, which is now a wrong key due to the invalid characters in the sequence. This problem actually arises from the wrong database representation (varchar instead of bytea) because it's otherwise considered as an invalid utf-8 sequence. I have tried to replace the invalid characters using some sort of split-modify-concat approach, but all I get is something without any backslash inside the sequence, because I can't insert a single backslash into a bytestring.
I really ask for your help.
Perhaps using read
will work for you:
import Data.ByteString.Char8 as BS
bad = BS.pack "\"\\159\\DEL*\\150\\222/\\129vr\\205\\241=mA\\192\\184\""
good = read (BS.unpack bad) :: BS.ByteString
-- returns: "\159\DEL*\150\222/\129vr\205\241=mA\192\184"
You can also use readMaybe
instead for safer parsing.