in reply to Question on Regular Expression

Based on the discussion in this thread I've ignored the regexes in the OP and instead pieced together the various examples given.

#!/usr/bin/env perl use warnings; use strict; use Test::More; sub parse { my ($str) = @_; my @m = $str =~ m{ ^ (?<P_ROOTCODE>\w+?) (?: (?<DAY1>\d) (?<P_MON_CODE>\w)? (?<P_NEW_MON_CODE>\w)? )? $ }x; note explain { $str => \%+ }; # debug output @m = map {$_//''} @m; # undef -> "" (optional) return \@m; } is_deeply parse("RS"), ["RS","","",""]; is_deeply parse("RC1XY"), ["RC","1","X","Y"]; is_deeply parse("RW12QW1X"), ["RW12QW", "1", "X", ""]; is_deeply parse("Sample1Repeat1A"), ["Sample1Repeat", "1", "A", ""]; is_deeply parse("Sample2Repeat2"), ["Sample2Repeat", "2", "", ""]; is_deeply parse("Sample3Repeat"), ["Sample3Repeat", "", "", ""]; is_deeply parse("4SampleRepeat"), ["4SampleRepeat", "", "", ""]; is_deeply parse("4SampleRepeat4"), ["4SampleRepeat", "4", "", ""]; is_deeply parse("5SampleRepeat5D"), ["5SampleRepeat", "5", "D", ""]; done_testing;

Sample output:

# { # 'RS' => { # 'P_ROOTCODE' => 'RS' # } # } ok 1 # { # 'RC1XY' => { # 'DAY1' => '1', # 'P_MON_CODE' => 'X', # 'P_NEW_MON_CODE' => 'Y', # 'P_ROOTCODE' => 'RC' # } # } ok 2 # { # 'RW12QW1X' => { # 'DAY1' => '1', # 'P_MON_CODE' => 'X', # 'P_ROOTCODE' => 'RW12QW' # } # } ok 3 ... ok 9 1..9

If that still doesn't suit your needs, add more test cases.

Replies are listed 'Best First'.
Re^2: Question on Regular Expression
by AnomalousMonk (Archbishop) on Dec 30, 2014 at 18:38 UTC

    FWIW, here's another variation. It has the advantage of producing empty strings rather than undefined values for absent pattern elements, so no need for a conversion step. It also has the advantage, if such it be, of not using named captures with the possible overhead of tied-hashery. It passes all tests above.

    $string =~ m{ \A ([[:alnum:]]+?) (?= (?: \d+ [[:upper:]]{0,2})? \z) (\d*) ([[:upper:]]?) ([[:upper:]]?) \z }xms;


    Give a man a fish:   <%-(-(-(-<

Re^2: Question on Regular Expression
by sjain (Initiate) on Dec 29, 2014 at 21:50 UTC

    THANK YOU VERY MUCH !!! I really appreciate your prompt and quick response.