Haskell:parsec键值对(键:值)

时间:2012-08-19 13:02:31

标签: haskell parsec

如何使用parsec将包含键和值的文件解析为[[(String, String)]]

key1: value 1 key2: value 2
key1: value 1 key2: value 2
key1: value 1 key2: value 2

键是一个单词,值可以是更多单词。

我试过了

tag :: GenParser Char st Tag
tag = do
  name <- key
  value <- manyTill anyChar (try key)
  return (name, value)

key :: GenParser Char st String
key = do
  name <- many (noneOf ": ")
  char ':'
  return name

> parse (many tag) "" "key1: value 1 key2: value 2"
Right [("key1"," value 1 ")]

1 个答案:

答案 0 :(得分:2)

我更改了tag函数来测试换行符和下一个键,这对我有用。

tag :: GenParser Char st Tag
tag = do
  name <- key
  value <- manyTill anyChar ((test newline) <|> (test key))
  return (name, strip value)

test :: GenParser Char st a -> GenParser Char st ()
test p = lookAhead $ try p >> return ()

key :: GenParser Char st String
key = do
  name <- many1 (noneOf ": \n\r")
  char ':'
  return name