使用 parsec 按分号解析字符串

Parse string by semicolon using parsec

这是我的任务之一。解析器 getList 假设下一步工作

GHCi> parseTest getList "1;234;56"
["1","234","56"]
GHCi> parseTest getList "1;234;56;"
parse error at (line 1, column 10):
unexpected end of input
expecting digit
GHCi> parseTest getList "1;;234;56"
parse error at (line 1, column 3):
unexpected ";"
expecting digit

我的解决方案getList = many digit `sepBy1` char ';'是这样工作的

*Main> test1
["1","234","56"]
*Main> test2
["1","234","56",""]
*Main> test3
["1","","234","56"]

不正确,我不知道如何处理双引号的情况。

试试这个:

getList = do
    many1 digit
    many $ do
       char ';'
       many1 digit

使用 megaparsec(我推荐 parsec):

getList = some digitChar `sepBy1` char ';'

这意味着 "at least one digit, at least one time, separated by semicolons"。请注意,我在您尝试使用 many.

的地方使用 some
ghci> parse getList "" "123;456"
Right ["123", "456"]
ghci> parse getList "" "123;;456"
Left (ParseError {errorPos = SourcePos {sourceName = "", sourceLine = Pos 1, sourceColumn = Pos 5} :| [], errorUnexpected = fromList [Tokens (';' :| "")], errorExpected = fromList [Label ('d' :| "igit")], errorCustom = fromList []})

你的问题是什么 many digit 它是接受零个或多个数字的解析器。例如,您应该使用 many1 digit。所以一起:

getList = many1 digit `sepBy` char ';'