haskell正则表达式替换

muh*_*ten 23 regex haskell

尽管Haskell 的正则表达式匹配引擎数量非常庞大,但我能找到的唯一一个可以替代的引擎是Text.Regex,虽然体面,但是我还是喜欢从pcre那里得到的一些东西.是否有任何基于pcre的包可以替代,还是我坚持这个?

rlp*_*ell 5

对于在其他所有现代语言都有琐碎的方法来完成实际工作的人们来说,我不认为“随心所欲”是一个合理的答案。包括计划。这是一些实际资源;我的代码来自一个项目,在该项目中,由于原因,我试图基于对qq中的“括号”内的函数调用函数,以文本替换“ qql foo bar baz qq”。

最佳选择:重载pcre:

      let newBody = gsub [re|\s(qq[a-z]+)\s(.*?)\sqq\s|] (unWikiReplacer2 titles) body in do
[snip]
unWikiReplacer2 :: [String] -> String -> [String] -> String
unWikiReplacer2 titles match subList = case length subList > 0 of
        True -> " --" ++ subList!!1 ++ "-- "
        False -> match
Run Code Online (Sandbox Code Playgroud)

请注意,pcre-heavy 直接支持任何字符串类型的基于函数的替换。很好。

另一个选择:pcre-light具有一个小的功能,该功能可以工作,但性能却不完全相同:

    let newBody = replaceAllPCRE "\\s(qq[a-z]+)\\s(.*?)\\sqq\\s" (unWikiReplacer titles) body in do
[snip]
unWikiReplacer :: [String] -> (PCRE.MatchResult String) -> String
unWikiReplacer titles mr = case length subList > 0 of
        True -> " --" ++ subList!!1 ++ "-- "
        False -> PCRE.mrMatch mr
    where
        subList = PCRE.mrSubList mr

-- A very simple, very dumb "replace all instances of this regex
-- with the results of this function" function.  Relies on the
-- MatchResult return type.
--
-- https://github.com/erantapaa/haskell-regexp-examples/blob/master/RegexExamples.hs
-- was very helpful to me in constructing this
--
-- I also used
-- https://github.com/jaspervdj/hakyll/blob/ea7d97498275a23fbda06e168904ee261f29594e/src/Hakyll/Core/Util/String.hs
replaceAllPCRE :: String              -- ^ Pattern
           -> ((PCRE.MatchResult String) -> String)  -- ^ Replacement (called on capture)
           -> String              -- ^ Source string
           -> String              -- ^ Result
replaceAllPCRE pattern f source =
    if (source PCRE.=~ pattern) == True then
      replaceAllPCRE pattern f newStr
    else
      source
    where
        mr = (source PCRE.=~ pattern)
        newStr = (PCRE.mrBefore mr) ++ (f mr) ++ (PCRE.mrAfter mr)
Run Code Online (Sandbox Code Playgroud)

他人的修正:http: //0xfe.blogspot.com/2010/09/regex-substitution-in-haskell.html

另一个,这次被嵌入到一个主要的库中:https : //github.com/jaspervdj/hakyll/blob/master/src/Hakyll/Core/Util/String.hs

另一个用于此目的的软件包:https : //hackage.haskell.org/package/pcre-utils


Chr*_*icz 2

regex-base 中的正则表达式 API 对于要匹配的字符容器是通用的。一般性地进行某种拼接来实现替换将很难提高效率。我不想提供蹩脚的通用例程。

编写一个小函数来完全按照您想要的方式进行替换是一个更好的主意,并且可以将其编写为与您的容器相匹配。