Using regular expressions to compare numbers

后端 未结 2 665
天命终不由人
天命终不由人 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条回答
  • 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?)?)$/
    
    0 讨论(0)
  • 2021-01-13 05:34

    You're going to need to generate the expression for each bounding number. Let's say there were a regular expression that would do the job. Then that regular expression would have to be able to take as input some sequence of characters. However, we know that regular expressions and finite state automata are equivalent, so this is the same as saying we can construct an FSM since the possible number is unbounded, that would require an unbounded number of states, which contradicts the definition of FSA.

    0 讨论(0)
提交回复
热议问题