mod_alex has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

Can anyone of you advise me if there is some module on CPAN or algorithm to search incremental expressions with regexps or by some predefined pattern

ie "4321234" =~ /(\d)\A1\A2\A3/ where we assume that A1 = $1 + 1 , A2 = A1 + 1, ...

My problem is I should implement some algorithm that returns a category of a given number string. ie

get_category("10000") = 10 # best category get_category("12345") = 10 # good category get_category("54321") = 8 # average category

So I want to set some rools for each category with regexps or regexp like patterns. The only problem is how to search incremental expressions with regexps or how to effectively implement it by myself
Thanx, Alex

Replies are listed 'Best First'.
Re: regexp for searching incremental expressions
by hv (Prior) on Mar 12, 2004 at 13:10 UTC

    As tomte suggests, you can achieve this using deferred evaluation; the trick is to take advantage of the special variable $^N, which refers to "the most recently closed capture" in the match so far.

    Using this, we get for example:

    % perl -le 'print $& if shift =~ /(\d)(((??{$^N + 1})))+/' 4321234 1234 %

    This works because the first time through the eval we have seen (for example) the digit '1', so we return '2' as the next thing to match; if we match it, that match is itself captured and becomes the last thing captured, so the next time into the eval $^N is '2' and we return '3' as the new thing to match.

    Note firstly that $^N was introduced in perl-5.8.0, so you won't be able to use this with earlier versions; secondly, enabling warnings gives the unexpected complaint:

    (((??{$^N + 1})))+ matches null string many times before HERE mark in +regex m/((\d)(((??{$^N + 1})))+ << HERE )/ at -e line 1.
    .. which looks like a bug, and you can safely ignore that warning in this case.

    Hugo

Re: regexp for searching incremental expressions
by Tomte (Priest) on Mar 12, 2004 at 11:11 UTC

    You may could experiment with (??{ code })

    #!/usr/bin/perl my $test = "4321234"; if ($test =~ m/(\d)((??{ $1 + 1}))/) { print "matched $1 $2 \n"; } __END__ matched 1 2

    regards,
    tomte


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

      I guess you are right
      Thanx, Alex
Re: regexp for searching incremental expressions
by matija (Priest) on Mar 12, 2004 at 11:08 UTC
    The only regexp pattern I can think of that would implement what you're looking for would be something like /1234|2345|3456|4567|5678|6789/ which would become rather unmanagable if you wanted it to work for really long matches.