简体   繁体   中英

Antlr string matching order

I'm triying to use ANTLR with a kind of file where the value to retrieve can be any sequence of chars excluding { and }.

text = {Valid;String}
text = {Another"Valid"-String}

But now VALUE is matching the line from the begining:

line 1:0 mismatched input 'text = ' expecting 'text'

What I'm doing wrong? Should not match with TEXT first?

grammar Example;

example : (TEXT '=' '{' VALUE '}')+;

WS : [ \t\r\n]+ -> skip ;

TEXT : 'text';

VALUE : ~('{'|'}')+;

我认为这是因为ANTLR 4会尝试匹配最长的字符串,因此“ text ...”将匹配到VALUE。

As Terence (The ANTLR Guy) mentioned, the rule VALUE greedily matches text = . You could let the VALUE rule include the braces instead of matching them as separate tokens:

example : (TEXT '=' VALUE)+;

WS : [ \t\r\n]+ -> skip ;

TEXT : 'text';

VALUE : '{' ~('{'|'}')+ '}';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM