2012-04-01 8 views
3

Bietet eine der Haskell PCRE-Bibliotheken eine Funktion, um Regex-Metazeichen in einer Zeichenfolge zu umgehen? I.e. eine Funktion, um einen String wie "[$ 100]" zu nehmen und ihn in "\ [\ $ 100 \]" umzuwandeln.Escape PCRE-Metazeichen in Haskell

Ich bin auf der Suche nach dem Äquivalent von Python re.escape, die ich nicht in Regex-pcre finden kann.

Antwort

2

Ich bin mir nicht bewusst, eine solche Funktion in einem der die PCRE-Bibliotheken, aber je nachdem, was Sie versuchen Sie PCRE zitieren verwenden könnte zu erreichen:

{-# 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 
+0

ich nicht bewusst war von PCRE-Zitat. Das hilft sehr, danke. – mskel