Sai Sai - 3 months ago 19
Perl Question

Extract data from string by perl

There is string "-test aaaa -machine bbb -from ccc"

How to extract "aaaa", "bbb", "ccc" using regular?

Even string is "-from   ccc   -test    aaaa    -machine bbb"

(Different order, several space....)

I had tried some code, but always got invalid data.

$str = "-test aaaa -machine bbb -from ccc";
$str =~ /-test\s*(.*)\s*/;


aaaa -machine bbb -from ccc

I also want to handle the below case

-test aa_aa -machine aab-baa-aba -from ccc

my @matches;
my $regex = qr/-\w+\s+([\w-]+)/;

my $string = q{-test aaaa -machine bbb -from ccc};
@matches = $string =~ /$regex/g;
print "Matches for first string are: @matches\n";

my $other_string = q{-from   ccc   -test    aaaa    -machine bbb};
@matches = $other_string =~ /$regex/g;
print "Matches for second string are: @matches\n";

my $third_string = q{-test aa_aa -machine aab-baa-aba -from ccc};
@matches = $third_string =~ /$regex/g;

print "Matches for third string are: @matches";