gpt4 book ai didi

haskell - Haskell 中的转义 PCRE 元字符

转载 作者:行者123 更新时间:2023-12-02 16:37:06 25 4
gpt4 key购买 nike

Haskell PCRE 库是否提供了转义字符串中正则表达式元字符的函数? IE。一个函数,用于将“[$100]”这样的字符串转换为“\[\$100\]”。

我正在寻找Python的re.escape的等价物,我似乎无法在 regex-pcre 中找到它。

最佳答案

我不知道有这样的功能PCRE 库,但取决于什么你正在尝试完成你可以使用PCRE 引用:

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

关于haskell - Haskell 中的转义 PCRE 元字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com