How can I change the order of substrings in a string?

How to do the following conversion to regex in perl?

British style   US style
"2009-27-02" => "2009-02-27"

I am new to Perl and don’t know much about regex, all I can think of is to extract the different parts of the “-” and then repeat the string concatenation since I need to do the conversion on the fly, I felt like my the approach will be rather slow and ugly.

+3
source share
3 answers
use strict;
use warnings;
use v5.10;

my $date = "2009-27-02";
$date =~ s/(\d{4})-(\d{2})-(\d{2})/$1-$3-$2/;
say $date;
+13
source

You asked about regex, but for such an obvious replacement, you could also create a function splitand parse. On my machine, it's about 22% faster:

my @parts = split '-', $date;
my $ndate = join( '-', @parts[0,2,1] );

You can also store different orders, for example:

my @ymd = qw<0 2 1>;
my @mdy = qw<2 1 0>;

, :

my $ndate = join( $date_separator, @date_parts[@$order] );

.

+5

You can also use Date :: Parse to read and convert dates. See this question for more information.

+4
source

Source: https://habr.com/ru/post/1727681/


All Articles