Using regular expressions to compare numbers

后端 未结 2 669
天命终不由人
天命终不由人 2021-01-13 04:36

So this is an obvious case of \"you\'re doing it wrong\". I don\'t actually intend on doing this, but a conversation at work spurred this question:

C

2条回答
  •  旧时难觅i
    2021-01-13 05:19

    This is quite easy.

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use Regexp::Assemble;
    
    for my $n (@ARGV)  {
        my $asm = new Regexp::Assemble;
        for (1 .. $n) { $asm->add($_) }
        for ($asm->re){
            s/\)$/\$/;
            s/^[^:]*:/^/;
            print "$n => /$_/\n";
        }
    }
    

    Now run it to find the pattern that matches integers between 1 and that number:

    $ perl /tmp/ra 5 15 153 401 1144
    5 => /^[12345]$/
    15 => /^(?:[23456789]|1[012345]?)$/
    153 => /^(?:1(?:[6789]|5[0123]?|0\d?|1\d?|2\d?|3\d?|4\d?)?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)$/
    401 => /^(?:1(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|2(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|3(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|4(?:[123456789]|0[01]?)?|5\d?|6\d?|7\d?|8\d?|9\d?)$/
    1144 => /^(?:1(?:0(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|1(?:[56789]|4[01234]?|0\d?|1\d?|2\d?|3\d?)?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|2(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|3(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|4(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|5(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|6(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|7(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|8(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?|9(?:0\d?|1\d?|2\d?|3\d?|4\d?|5\d?|6\d?|7\d?|8\d?|9\d?)?)$/
    

提交回复
热议问题