Perl6 Regex Match Num

青春壹個敷衍的年華 提交于 2020-08-27 06:50:18

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48972033/perl6-regex-match-num

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!