CocoRuby
CocoRuby

Reputation: 57

Perl alphabetic sort with alphanumeric string and regex

I am trying to sort alphanumeric string with perl and am facing the following problem:

Strings are like this: "XXXXX-1.0.0" where numbers can be on one or two digits and are representing release versions.

My problem is that when I have the two following strings: - XXXXX-1.9.9 - XXXXX-1.10.0 XXXXX-1.9.9 is considered as greater than XXXXX-1.10.0 since 9 is greater than 1. So I am trying to force numbers to be on two digits with a regexp.

There is the piece of code I am testing:

my $string = "XXXXXX-1.9.9";
my $pre = "0";
$string =~ s/(\.|-)+(\d{1})($|\.)/$1$pre$2$3/g;
print "$string\n";

This gives me the result "XXXXXX-01.9.09" which is not what I am looking for since it will not be sorted correctly. So I have to do that:

my $string = "XXXXXX-1.9.9";
my $pre = "0";
$string =~ s/(\.|-)+(\d{1})($|\.)/$1$pre$2$3/g;
$string =~ s/(\.|-)+(\d{1})($|\.)/$1$pre$2$3/g;
print "$string\n";

To get "XXXXXX-01.09.09"

My question is double: - Is there a way to sort my strings with Perl without using regex? - If I have to use regex is there a way to write it so that I do not have to execute it twice?

Thank you in advance.

Upvotes: 0

Views: 475

Answers (1)

choroba
choroba

Reputation: 241938

You can use look around assertions to make sure there are not digits around the digit you are replacing without moving the position over the neighbouring characters.

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @strings = qw( XXXXX-1.9.9
                  XXXXX-1.9.10
                  XXXXX-1.10.0 );

s/(?<=[^0-9]) ([0-9]) (?=[^0-9]|$) /0$1/xg for @strings;
@strings = sort @strings;
s/(?<=[^0-9]) 0+ ([0-9]) /$1/xg for @strings;

say for @strings;

Upvotes: 1

Related Questions