[antlr-interest] Distinguish between number and value

shmuel siegel antlr at shmuelhome.mine.nu
Sat Nov 3 12:44:38 PDT 2007


Jim Idle wrote:
>
> Usually, you would do such things in the parser, but in this instance 
> you can actually do it in the lexer if you want. If you leave it to 
> the pasere then you would need a keyword ‘px’, which may be awkward 
> elsewhere of course:
>
It is actually not so easy in the parser unless "123 px" is a legal 
pixel size (notice the space). It really is best to do this in the lexer.
>
> tokens
>
> {
>
> PIXELS;
>
> }
>
> // Parser goes here
>
> NUMBER
>
> : (‘0’..’9’)+
>
> (
>
> ((‘px’)=> ‘px’) { $type = PIXELS; }
>
> | // Just a number after all
>
> )
>
> ;
>
> Should work fine for you and will avoid lexing errors if the input is 
> 89p by mistake, that would go back to the parser as two tokens and it 
> will error out gracefully. Note, that you may get a warning about the 
> PIXELS token, which you can ignore.
>
> There are other approaches of course, such as leaveing the px to go 
> back as a token like ID, then in the parser allowing:
>
> NUMBER ID { see if ID text is ‘px’ else error}
>
> Hope that helps,
>
> Jim
>
> *From:* antlr-interest-bounces at antlr.org 
> [mailto:antlr-interest-bounces at antlr.org] *On Behalf Of *Adrian Ber
> *Sent:* Friday, November 02, 2007 10:07 AM
> *To:* antlr-interest at antlr.org
> *Subject:* [antlr-interest] Distinguish between number and value
>
> I'm using a CSS grammar and wondering how can I write a rule to 
> distinguish between a number and a value. If I have the input "123" 
> and "123px" I want to know that "123" is a number and "123px" is a 
> length.
>
> I'm new to ANTLR and using v3.
>
> Thanks a lot,
>
> A.
>
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>




More information about the antlr-interest mailing list