How to define a regular expression pattern as a constant in Perl?

I want to define the regexp constant in my script at the top and use it later to check the format of the date string.

my date string will be defined as

$ a = "2013-03-20 11: 09: 30.788";

but it failed. how should i do this?

 use strict;
 use warnings;


 use constant REGEXP1 => "/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/";

 $a="2013-03-20 11:09:30.788";
 if(not $a=~&REGEXP1){
         print "not"

 }else{
         print "yes"

 }
 print "\n";
+5
source share
2 answers

First, let's look at "/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/";If you had warnings, you should have received:

Unrecognized escape \ d passed through at C: \ temp \ jj.pl line 7.
Unrecognized escape \ D passed through at C: \ temp \ jj.pl line 7.
Unrecognized escape \ d passed through at C: \ temp \ jj.pl line 7.
...

REGEXP1, /^d{4}Dd{2}Dd{2}Dd{2}Dd{2}Dd{2}Dd{3} (* wait, $/?). , , .

"/^\\d{4}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{2}\\D\\d{3}\$/" , . , regexp quote, qr:

#!/usr/bin/env perl

use 5.012;
use strict;
use warnings;

use constant REGEXP1 => qr/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/;

my $s = "2013-03-20 11:09:30.788";

say $s =~ REGEXP1 ? 'yes' : 'no';

: \d \d , [0-9] [^0-9], . , , :

use constant REGEXP1 => qr{
    \A
    (?<year>  [0-9]{4} ) -
    (?<month> [0-9]{2} ) -
    (?<day>   [0-9]{2} ) [ ]
    (?<hour>  [0-9]{2} ) :
    (?<min>   [0-9]{2} ) :
    (?<sec>   [0-9]{2} ) [.]
    (?<msec>  [0-9]{3} )
    \z
}x;

, . , DateTime:: Format:: Strptime.

#!/usr/bin/env perl

use 5.012;
use strict;
use warnings;

use DateTime::Format::Strptime;

my $s = "2013-03-20 11:09:30.788";

my $strp = DateTime::Format::Strptime->new(
    pattern => '%Y-%m-%d %H:%M:%S.%3N',
    on_error => 'croak',
);

my $dt = $strp->parse_datetime($s);
say $strp->format_datetime($dt);
+9

Perl ? 5.8.8 ( 5.004), :

use constant REGEXP1 => qr/^\d{4}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{2}\D\d{3}$/;
+3

All Articles