Escape PCRE metacharacters in Haskell
Question: Do any of the Haskell PCRE libraries provide a function to escape regex
metacharacters in a string? I.e. a function to take a string like "[$100]" and
turn it into "\\[\$100\\]".

I'm looking for the equivalent of Python's
[re.escape](http://docs.python.org/library/re.html#re.escape), which I can't
seem to find in regex-pcre.


Answer: I'm not aware of such a function in any of the PCRE libraries, but depending
on what you are trying to accomplish you could use PCRE quoting:

    
    
    {-# LANGUAGE OverloadedStrings #-}
    
    import qualified Data.ByteString.Char8 as B
    import Text.Regex.PCRE
    
    
    quotePCRE bs = B.concat [ "\\Q" , bs , "\\E" ]
    
    -- Of course, this won't work if the
    -- string to be quoted contains `\E` ,
    -- but that would be much eaiser to fix
    -- than writing a function taking into
    -- account all the necessary escaping.
    
    literal = "^[$100]$"
    
    quoted = quotePCRE literal
    
    main :: IO ()
    main = do B.putStr "literal: " >> B.putStrLn literal
    
              -- literal: ^[$100]$
    
              B.putStr "quoted: "  >> B.putStrLn quoted
    
              -- quoted: \Q^[$100]$\E
    
              putStrLn "literal =~ literal :: Bool"
              print ( literal =~ literal :: Bool )
    
              -- literal =~ literal :: Bool
              -- False
    
              putStrLn "literal =~ quoted :: Bool"
              print ( literal =~ quoted :: Bool )
    
              -- literal =~ quoted :: Bool
              -- True
    

