Haskell - Parsec 解析 <p> 元素

Mar*_*tin 3 html parsing haskell functional-programming parsec

我正在使用Text.ParserCombinators.ParsecText.XHtml来解析这样的输入:

这是第一段示例\n
两行\n
\n
这是第二段\n

我的输出应该是:

<p>This is the first paragraph example\n with two lines\n</p> <p>And this is the second paragraph\n</p>

我定义:


line= do{
        ;t<-manyTill (anyChar) newline
        ;return t
        }

paragraph = do{
        t<-many1 (line) 
        ;return ( p << t )
    }

Run Code Online (Sandbox Code Playgroud)

但它返回:

<p>This is the first paragraph example\n with two lines\n\n And this is the second paragraph\n</p>

怎么了?有任何想法吗?

谢谢!

hza*_*zap 5

manyTill 的文档中,它运行第一个参数零次或多次,因此连续 2 个换行符仍然有效并且您的line解析器不会失败。

您可能正在寻找类似many1Till(例如many1vs many)但它似乎不存在于 Parsec 库中,因此您可能需要自己动手:(警告:我在这台机器上没有 ghc,所以这是完全未经测试)

many1Till p end = do
    first <- p
    rest  <- p `manyTill` end
    return (first : rest)
Run Code Online (Sandbox Code Playgroud)

或者更简洁的方式:

many1Till p end = liftM2 (:) p (p `manyTill` end)
Run Code Online (Sandbox Code Playgroud)

  • 问题是如果你将它与 `anyChar` 一起用作 `p` 它仍然匹配两个换行符,因为 `first &lt;- p` 消耗了第一个换行符。 (3认同)