开发者

Ignoring C-style comments in a Scala combinator parser

开发者 https://www.devze.com 2023-03-05 02:17 出处:网络
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 welc开发者_运维问答ome.

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 welc开发者_运维问答ome.

I'm currently simply extending JavaTokenParsers.


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

精彩评论

暂无评论...
验证码 换一张
取 消