in reply to Re: Convert an array of numbers into a range
in thread Convert an array of numbers into a range

I am thinking @ra = qw(0001 0002 0003 011 012 013 015); or added couple numbers :) @ra = qw(0001 0002 0003 011 012 013 015 16 17 18 20); How is regex be structured? Thanks a lot.
  • Comment on Re^2: Convert an array of numbers into a range

Replies are listed 'Best First'.
Re^3: Convert an array of numbers into a range
by Anonymous Monk on Jul 22, 2016 at 00:49 UTC

    For older perls without the /r

    #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1168288 use strict; use warnings; my @ra = qw(0001 0002 0003 011 012 013 015 16 17 18 20); $_ = join ',', @ra; s/\b(\d+)(?{$1})\K(?:,(\d+)\b(??{++$^R!=$2}))+/-$2/g; print;

      this sort of works.

      result: 0001-0003,011-013,015-18,20

      should be: 0001-0003,011-013,015,16-18,20

        Changing the rules in the middle of the game?

        Next time give exact desired output when you pose a problem.

        #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1168288 use strict; use warnings; my @ra = qw(0001 0002 0003 011 012 013 015 16 17 18 20); $_ = join ',', @ra; s/\b(\d+)(?{$1})\K(?:,(\d+)\b(??{++$^R!=$2||length$1!=length$2}))+/-$2 +/g; print;
Re^3: Convert an array of numbers into a range
by Anonymous Monk on Jul 22, 2016 at 00:37 UTC
    #!/usr/bin/perl -l # http://perlmonks.org/?node_id=1168288 use strict; use warnings; my @ra = qw(0001 0002 0003 011 012 013 015 16 17 18 20); print join(',', @ra) =~ s/\b(\d+)(?{$1})\K(?:,(\d+)\b(??{++$^R!=$2}))+ +/-$2/gr;