请注意,在发布此问题之后,我设法自己得出了一个解决方案。有关我的最终答案,请参阅此问题的结尾。
目前,我正在为org-mode文档开发一个小型解析器,在这些文档中,标题可以具有标题,并且可以有选择地在标题的处包含标签列表:
* Heading :foo:bar:baz:
但是,我很难为此编写解析器。以下是我目前正在使用的内容:
import Control.Applicative
import Text.ParserCombinators.Parsec
data Node = Node String [String]
deriving (Show)
myTest = parse node "" "Some text here :tags:here:"
node = Node <$> (many1 anyChar) <*> tags
tags = (char ':') >> (sepEndBy1 (many1 alphaNum) (char ':'))
<?> "Tag list"
虽然我的简单
tags
解析器可以工作,但它在node
的上下文中不起作用,因为所有字符都用完了标题的解析头(many1 anyChar
)。此外,由于标题中的noneOf ":"
有效,因此我无法将此解析器更改为使用:
。实际上,只有在行尾的标记列表中,它才是特殊的。有什么想法可以解析此可选数据吗?
顺便说一句,这是我第一个真正的Haskell项目,因此,如果Parsec甚至不是适合该工作的工具-请随时指出并提出其他选择!
好的,我现在有了一个完整的解决方案,但是它需要重构。以下作品:
import Control.Applicative hiding (many, optional, (<|>))
import Control.Monad
import Data.Char (isSpace)
import Text.ParserCombinators.Parsec
data Node = Node { level :: Int, keyword :: Maybe String, heading :: String, tags :: Maybe [String] }
deriving (Show)
parseNode = Node <$> level <*> (optionMaybe keyword) <*> name <*> (optionMaybe tags)
where level = length <$> many1 (char '*') <* space
keyword = (try (many1 upper <* space))
name = noneOf "\n" `manyTill` (eof <|> (lookAhead (try (tags *> eof))))
tags = char ':' *> many1 alphaNum `sepEndBy1` char ':'
myTest = parse parseNode "org-mode" "** Some : text here :tags: JUST KIDDING :tags:here:"
myTest2 = parse parseNode "org-mode" "* TODO Just a node"
最佳答案
import Control.Applicative hiding (many, optional, (<|>))
import Control.Monad
import Text.ParserCombinators.Parsec
instance Applicative (GenParser s a) where
pure = return
(<*>) = ap
data Node = Node { name :: String, tags :: Maybe [String] }
deriving (Show)
parseNode = Node <$> name <*> tags
where tags = optionMaybe $ optional (string " :") *> many (noneOf ":\n") `sepEndBy` (char ':')
name = noneOf "\n" `manyTill` try (string " :" <|> string "\n")
myTest = parse parseNode "" "Some:text here :tags:here:"
myTest2 = parse parseNode "" "Sometext here :tags:here:"
结果:
*Main> myTest
Right (Node {name = "Some:text here", tags = Just ["tags","here",""]})
*Main> myTest2
Right (Node {name = "Sometext here", tags = Just ["tags","here",""]})
关于最后分析带有可选数据的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4996514/