How can I store regex captures in an array in Perl?

后端 未结 7 1214
孤城傲影
孤城傲影 2020-12-01 03:38

Is it possible to store all matches for a regular expression into an array?

I know I can use ($1,...,$n) = m/expr/g;, but it seems as though that can on

7条回答
  •  难免孤独
    2020-12-01 03:56

    Note that if you know the number of capturing groups you need per match, you can use this simple approach, which I present as an example (of 2 capturing groups.)

    Suppose you have some 'data' like

    my $mess = <<'IS_YOURS';
    Richard     Rich
    April           May
    Harmony             Ha\rm
    Winter           Win
    Faith     Hope
    William         Will
    Aurora     Dawn
    Joy  
    IS_YOURS
    

    With the following regex

    my $oven = qr'^(\w+)\h+(\w+)$'ma;  # skip the /a modifier if using perl < 5.14
    

    I can capture all 12 (6 pairs, not 8...Harmony escaped and Joy is missing) in the @box below.

    my @box = $mess =~ m[$oven]g;
    

    If I want to "hash out" the details of the box I could just do:

    my %hash = @box;
    

    Or I just could have just skipped the box entirely,

    my %hash = $mess =~ m[$oven]g;
    

    Note that %hash contains the following. Order is lost and dupe keys (if any had existed) are squashed:

    (
              'April'   => 'May',
              'Richard' => 'Rich',
              'Winter'  => 'Win',
              'William' => 'Will', 
              'Faith'   => 'Hope',
              'Aurora'  => 'Dawn'
    );
    

提交回复
热议问题