开发者

ANTLR Matching all tokens except

开发者 https://www.devze.com 2023-03-28 14:24 出处:网络
Is there any way to match a token in antlr except a specific one? I have a rule which states that a \'_\' can be an ID. Now I have a specific situation in which I want to match an ID, but in this par

Is there any way to match a token in antlr except a specific one?

I have a rule which states that a '_' can be an ID. Now I have a specific situation in which I want to match an ID, but in this particular case I want it to ignore the '_' alter开发者_如何学Gonative. Is it possible?


I think something like

(ID {!$ID.text.equals("_")}?)

should do it (if you are using Java as target language). Otherwise you will have to write that semantic predicate in a way that your language understands it.

In short, this will check whether the text does not equal "_" and only then will the subrule match.

Another possible way to do this:

id: ID
  | '_'
  ;

ID: // lexer rule to match every valid identifier EXCEPT '_' ;

That way, whenever you mean "either '_' or any other ID", you use id to match this, if you disallow "_", you can use _.

0

精彩评论

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

关注公众号