1

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

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

key是一个词,value可以是多个词。

我努力了

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 ")]
4

1 回答 1

2

I have changed the tag function to test both newline and next key, and that works for me.

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
于 2012-08-19T15:04:52.943 回答