2

开始学习 Haskell,我决定熟悉 Parsec,但是出现了问题。我正在尝试以 FB2 的格式实现对书籍的解析。对常规标签(文本)很好,但当标签内的标签 - 不起作用。

import Text.ParserCombinators.Parsec

data FB2Doc = Node String FB2Doc
            | InnText String
            deriving (Eq,Show)

parseFB2 :: GenParser Char st [FB2Doc]
parseFB2 = many test

test :: GenParser Char st FB2Doc
test = do name <- nodeStart
          value <- getvalue
          nodeEnd
          return $ Node name value

nodeStart = do char '<'
               name <- many (letter <|> digit <|> oneOf "-_")
               char '>'
               return name

nodeEnd = do string "</"
             many (letter <|> digit)
             char '>'
             spaces 
gettext = do x <- many (letter <|> digit <|> oneOf "-_")
             return $ InnText x 

getvalue = do (nodeStart >> test) <|> gettext <|> return (Node "" (InnText ""))
main = do
         print $ parse parseFB2 "" "<h1><a2>ge</a2></h1> <genre>history_russia</genre>"
4

1 回答 1

1

我想你想要这个:

getvalue = try test <|> gettext

try节点需要:"<bla></bla>"test将消耗'<'of </bla>,并且try允许回溯。

于 2011-10-10T12:43:44.643 回答