Perl6 Regex Match Num

I would like to match any Num from part of a text string. Until now, this (stolen from https://docs.perl6.org/language/regexes.html#Best_practices_and_gotchas ) is doing 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/; 

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

+5
source share
1 answer

If you can make reasonable assumptions about the number, for example, it is limited by word boundaries, you can do something like this:

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

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

+4
source

Source: https://habr.com/ru/post/1275568/


All Articles