Mar*_*tin 3 html parsing haskell functional-programming parsec
我正在使用Text.ParserCombinators.Parsec和Text.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>
怎么了?有任何想法吗?
谢谢!
从manyTill 的文档中,它运行第一个参数零次或多次,因此连续 2 个换行符仍然有效并且您的line
解析器不会失败。
您可能正在寻找类似many1Till
(例如many1
vs 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)