Perl6 正则表达式匹配数 [英] Perl6 Regex Match Num

查看:68
本文介绍了Perl6 正则表达式匹配数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文本字符串的一部分匹配任何 Num.到目前为止,这个(从 https://docs.perl6.org/language/regexes.html#Best_practices_and_gotchas) 完成工作...

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/;

这似乎是对轮子的很多(容易出错的)改造.是否有 perl6 技巧来匹配语法中的内置类型(Num、Real 等)?

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?

推荐答案

如果你可以对数字做出合理的假设,比如它被单词边界分隔,你可以这样做:

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 +"$/" }>
}

此正则表达式的最后一行将 Match ("$/"),然后尝试将其转换为数字 (+).如果它有效,它返回一个定义的值,否则返回 Failure.这种字符串到数字的转换识别与 Perl 6 语法相同的语法.<?{ ... }> 结构是一个断言,所以如果内部的表达式返回一个假值,它会使匹配失败.

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.

这篇关于Perl6 正则表达式匹配数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆