我如何从Parsec的文件中去掉评论? [英] How would I strip out comments from a file with Parsec?

查看:117
本文介绍了我如何从Parsec的文件中去掉评论?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这么多:

  comment :: GenParser Char st()
comment =
(字符串 - >> manyTill anyChar换行符>>空格>> return())< |>
(string/ *>> manyTill anyChar(string* /)>> spaces>> return())

eatComments :: GenParser Char st字符串
eatComments =做
xs< - 许多(做
可选注释
x< - manyTill anyChar(尝试注释)
返回x)
返回$ intercalatexs

如果输入以注释结束,但它在结束时失败用别的东西。在这种情况下,错误消息就像

 不匹配(第13行,第1列):
意外的输入结束
期待 - 或/ *

所以解析器正在寻找在时间 eof 到达时发表评论。我需要一些帮助,找到正确的组合器,我需要在所有可能的情况下吃掉所有的注释。 可能使用类似的东西 eof

$ p $ comment :: GenParser Char st()
comment =
(string - >>> manyTill anyChar换行符>>空格>> return())< |>
(string/ *>> manyTill anyChar((try(string >> * /)>> return())< |> eof)>> spaces>> return())


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.

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 ())

这篇关于我如何从Parsec的文件中去掉评论?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆