Question

I'm trying to create a token for an odd number of spaces. This is what I have currently

TOKEN : {
< SPACE: " " > 
| < ODDSPACE: <SPACE> ((<SPACE>)(<SPACE>))* >
}

void Start() :
{}
{  
    <ODDSPACE>
}

This is fine for 3, 5, 7...etc spaces, but fails when I try using only once space. Any ideas why this is happening?

Was it helpful?

Solution

See question 3.3 of the JavaCC FAQ. http://www.engr.mun.ca/~theo/JavaCC-FAQ/javacc-faq-moz.htm#tth_sEc3.3

There are three golden rules for picking which regular expression to use to identify the next token:

  1. The regular expression must describe a prefix of the remaining input stream.
  2. If more than one regular expression describes a prefix, then a regular expression that describes the longest prefix of the input stream is used. (This is called the "maximal munch rule".)
  3. If more than one regular expression describes the longest possible prefix, then the regular expression that comes first in the .jj file is used.

In your case rule 3 applied. You can rewrite start as

void Start() :
{}
{  
    <ODDSPACE> | <SPACE> 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top