Ignoring C-style comments in a Scala combinator parser

孤人 提交于 2019-12-20 12:38:44

问题


What is the most simple way to make my parser respect (ignore) C-style comments. I'm interested in both comment types, though a solution for only one type is also welcome.

I'm currently simply extending JavaTokenParsers.


回答1:


You can use a simple regular expression, as long as you don't nest comments. Put it inside whiteSpace:

scala> object T extends JavaTokenParsers {
     |    protected override val whiteSpace = """(\s|//.*|(?m)/\*(\*(?!/)|[^*])*\*/)+""".r
     |    def simpleParser = ident+
     | }
defined module T

scala> val testString = """ident // comment to the end of line
     | another ident /* start comment
     | end comment */ final ident"""
testString: java.lang.String = 
ident // comment to the end of line
another ident /* start comment
end comment */ final ident

scala> T.parseAll(T.simpleParser, testString)
res0: T.ParseResult[List[String]] = [3.27] parsed: List(ident, another, ident, final, ident)


来源:https://stackoverflow.com/questions/5952720/ignoring-c-style-comments-in-a-scala-combinator-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!