代码之家  ›  专栏  ›  技术社区  ›  muhmuhten

haskell正则表达式替换

  •  23
  • muhmuhten  · 技术社区  · 16 年前

    尽管regex的数量惊人的多 匹配 Haskell的引擎,我能找到的唯一一个 代替 是 Text.Regex ,虽然不错,但却少了一些我喜欢的pcre。是否有任何基于pcre的软件包可以替代,或者我是否坚持这样做?

    2 回复  |  直到 16 年前
        1
  •  3
  •   Chris Kuklewicz    16 年前

    regex base中的正则表达式API对于要匹配的字符容器是通用的。一般性地进行某种剪接来实现替换是非常困难的。我不想提供一个糟糕的通用程序。

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

        2
  •  8
  •   rlpowell    11 年前

    所有其他现代语言 有一个很简单的方法。包括方案。这里有一些实际的资源;我的代码来自一个项目,在这个项目中,我试图用文本替换“qqlfoobar bazqq”,基于调用qq“括号”中的一个函数,因为原因。

          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
    

    注意pcre重 字符串类型。太好了。

    另一个选择:pcre灯有一个小功能,但不完全是

        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)
    

    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

        3
  •  0
  •   James Brock    6 年前

    我完全同意@rlpowell的观点

    我认为对于那些试图完成实际工作的人来说,“自己动手”并不是一个合理的答案,因为在这个领域里,其他所有现代语言都有一种微不足道的方式来完成这项工作。

    在撰写本文时,还有 Regex.Applicative.replace 对于regex替换,尽管它与Perl不兼容。

    对于使用解析器而不是正则表达式的模式匹配和替换,有 Replace.Megaparsec.streamEdit