我有以下代码,并且想在|中排除保留字作为标识符。
TOKEN : /* Numbers and identifiers */
{
< INT : (<DIGIT>)+ >
| < #DIGIT : ["0" - "9"] >
| < ID : (<LETTER>)+("_")*(<#DIGIT>)*(<LETTER>)* >
| < #LETTER : ["a" - "z", "A" - "Z"] >
}
TOKEN : { /* RESERVED WORDS */
<VARIABLE: "variable">
| <CONSTANT: "constant">
| <RETURN: "return">
| <INTEGER: "integer">
| <BOOLEAN: "boolean">
| <VOID: "void">
| <MAIN: "main">
| <IF: "if">
| <ELSE : "else">
| <TRUE: "true">
| <FALSE: "false">
| <WHILE: "while">
| <BEGIN: "begin">
| <END: "end">
| <IS: "is">
| <SKIP: "skip">
}
答案 0 :(得分:1)
当两个正则表达式都匹配最长的匹配项时,第一个赢。 (请参见JavaCC FAQ。)
因此解决方案很容易:重新订购产品:
TOKEN : { /* RESERVED WORDS */
<VARIABLE: "variable">
| <CONSTANT: "constant">
| <RETURN: "return">
| <INTEGER: "integer">
| ...
}
TOKEN : /* Numbers and identifiers */
{
< INT : (<DIGIT>)+ >
| < #DIGIT : ["0" - "9"] >
| < ID : (<LETTER>)+("_")*(<#DIGIT>)*(<LETTER>)* >
| < #LETTER : ["a" - "z", "A" - "Z"] >
}