简体   繁体   中英

grep a expression in an array of string with Perl

I'm trying to grep a special pattern in an array of strings.

My array of strings is like this :

@list=("First phrase with \"blabla - Word\" and other things "
      ,"A phrase without... "
      ,"Second phrase with \"truc - Word\" and etc... "
      ,"Another phrase without... "
      ,"Another phrase with \"thing - Word\" and etc... ");

and I tried to grep the pattern "..... - Word" with this function :

@keyw = grep { /\".* Word\"/} (@list);

and I have the following result :

print  (Dumper  (  @keyw));
$VAR1 = 'First phrase with "blabla - Word" and other things ';
$VAR2 = 'Second phrase with "truc - Word" and etc... ';
$VAR3 = 'Another phrase with "thing - Word" and etc... ';

My grep function is ok to grep the phrase but I would like to grep just the pattern and get the following result :

$VAR1 = '"blabla - Word"';
$VAR2 = '"truc - Word"';
$VAR3 = '"thing - Word"';

Do you know how to reach this result ?

Use map instead of grep :

my @keyw = map { /\"[^"]*? Word\"/ ? $& : () } @list;

It just returns $& (whole match) if the pattern matches and () (empty list) if it does not.
Little caveat: don't use $& with with Perl < 5.18.0.

Here's Casimir et Hippolyte 's simpler solution:

my @keyw = map { /(\"[^"]*? Word\")/ } @list;

It works since m// returns a list of captured groups.

Why can't we just use a normal loop?

use strict;
use warnings;

use Data::Dump;

my @phrases = (
    "First phrase with \"blabla - Word\" and other things ",
    "A phrase without... ",
    "Second phrase with \"truc - Word\" and etc... ",
    "Another phrase without... ",
    "Another phrase with \"thing - Word\" and etc... ",
);

my @matches;

for (@phrases) {
    next unless /("[^"]+Word")/;
    push(@matches, $1);
}

# prints ["\"blabla - Word\"", "\"truc - Word\"", "\"thing - Word\""]
dd(\@matches);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM