Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl6 Regex Match Num

Tags:

raku

I would like to match any Num from part of a text string. So far, this (stolen from from https://docs.perl6.org/language/regexes.html#Best_practices_and_gotchas) does the job...

    my token sign { <[+-]> }
    my token decimal { \d+ }
    my token exponent { 'e' <sign>? <decimal> }
    my regex float {
        <sign>?
        <decimal>?
        '.' 
        <decimal>
        <exponent>?
    }   
    my regex int {
        <sign>?
        <decimal>
    }   
    my regex num {
        <float>?
        <int>?
    }   
    $str ~~ s/( <num>? \s*) ( .* )/$1/;

This seems like a lot of (error prone) reinvention of the wheel. Is there a perl6 trick to match built in types (Num, Real, etc.) in a grammar?

like image 656
p6steve Avatar asked Feb 25 '18 09:02

p6steve


1 Answers

If you can make reasonable assumptions about the number, like that it's delimited by word boundaries, you can do something like this:

regex number {
   «     # left word boundary
   \S+   # actual "number"
   »     # right word boundary
   <?{ defined +"$/" }>
}

The final line in this regex stringifies the Match ("$/"), and then tries to convert it to a number (+). If it works, it returns a defined value, otherwise a Failure. This string-to-number conversion recognizes the same syntax as the Perl 6 grammar. The <?{ ... }> construct is an assertion, so it makes the match fail if the expression on the inside returns a false value.

like image 137
moritz Avatar answered Nov 04 '22 05:11

moritz