Matching numbers: any shortcut methods?

classic Classic list List threaded Threaded
2 messages Options
fge
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Matching numbers: any shortcut methods?

fge
Hello,

I have just started playing with parboiled. I want to write a simple parser for CSS color expressions.

I was wondering:

* are there rules to match a certain quantity of rules n times? For instance, a CSS hexadecimal color expression is a # followed by three or six hexadecimal digits. Is there a shortcut to this instead of writing Sequence(HexDigit(), HexDigit(), HexDigit())?
* are there rules to match a range of numbers? This time with RGB colors, one can have rgb(x, y, z) where all of x, y and z are greater than 0 and less than 255.
fge
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Matching numbers: any shortcut methods?

fge

Answer to self:

  • for repetitions, I have submitted an issue and had a go at implementing it as well (along with a very useful, I think, Join() rule);
  • for integer range checking, after reading some more, this is what I cooked up:
        static  Action RangeCheck(final int start, final int end)
        {
            if (start > end)
                throw new IllegalStateException();
    
            return new Action() {
                @Override
                public boolean run(final Context context)
                {
                    final int value;
    
                    try {
                        value = Integer.parseInt(context.getMatch());
                    } catch (NumberFormatException ignored) {
                        //Overflow
                        return false;
                    }
                    return value >= start && value <= end;
                }
            };
        }
        // ...
        Rule PositiveInteger(final int start, final int end)
        {
            return Sequence(OneOrMore(Digit()), RangeCheck(start, end));
        }
    

I guess this is not state of the art code, but it does the job... If it can be better, please let me know!

Loading...