How to check the ranges of numbers in ANTLR 3?
I know this might end up being language specific, so a Java or Python solution would be acceptable.
Given the grammar:
MONTH : DIGIT DIGIT ;
DIGIT : ('0'..'9') ;
I want a check constraint on MONTH
to ensure the value is between 01
and 12
. Where do I start looking, and how do I specify this constraint as a开发者_如何学Go rule?
You can embed custom code by wrapping {
and }
around it. So you could do something like:
MONTH
: DIGIT DIGIT
{
int month = Integer.parseInt(getText());
// do your check here
}
;
As you can see, I called getText()
to get a hold of the matched text of the token.
Note that I assumed you're referencing this MONTH
rule from another lexer rule. If you're going to throw an exception if 1 > month > 12
, then whenever your source contains an illegal month value, non of the parser rules will ever be matched. Although lexer- and parser rules can be mixed in one .g
grammar file, the input source is first tokenized based on the lexer rules, and once that has happened, only then the parser rules will be matched.
You can use this free online utility Regex_For_Range to generate a regular expression for any continuous integer range. For the values 01-12 (with allowed leading 0's) the utility gives:
0*([1-9]|1[0-2])
From here you can see that if you want to constrain this to just the 2-digit strings '01' through '12', then adjust this to read:
0[1-9]|1[0-2]
For days 01-31 we get:
0*([1-9]|[12][0-9]|3[01])
And for the years 2000-2099 the expression is simply:
20[0-9]{2}
精彩评论