问题
I have this much:
comment :: GenParser Char st ()
comment =
(string "--" >> manyTill anyChar newline >> spaces >> return ()) <|>
(string "/*" >> manyTill anyChar (string "*/") >> spaces >> return ())
eatComments :: GenParser Char st String
eatComments = do
xs <- many (do
optional comment
x <- manyTill anyChar (try comment)
return x)
return $ intercalate " " xs
This works if the input ends with a comment, but it fails if it ends with something else. In that case the error message is like
No match (line 13, column 1):
unexpected end of input
expecting "--" or "/*"
So the parser is looking for a comment by the time eof
arrives. I need some help finding the right combinators I need to eat up all the comments in all possible cases.
回答1:
Maybe use something like eof ?
comment :: GenParser Char st ()
comment =
(string "--" >> manyTill anyChar newline >> spaces >> return ()) <|>
(string "/*" >> manyTill anyChar ((try (string "*/") >> return ()) <|> eof) >> spaces >> return ())
回答2:
I hit on this which seems to work. But please feel free to critique:
comment :: GenParser Char st ()
comment =
(string "--" >> manyTill anyChar newline >> spaces >> return ()) <|>
(string "/*" >> manyTill anyChar (string "*/") >> spaces >> return ())
notComment = manyTill anyChar (lookAhead (comment <|> eof))
eatComments :: GenParser Char st String
eatComments = do
optional comment
xs <- sepBy notComment comment
optional comment
return $ intercalate "" xs
来源:https://stackoverflow.com/questions/12940490/how-would-i-strip-out-comments-from-a-file-with-parsec