PYPL
PYPL

Reputation: 1859

Array splitting with regex

I have an array that holds only one string, it's hash's value:

%hash = ("key"=>["Value1 unit(1), Value2 unit(2), Value3 unit"])

How to split the " unit"-s from the value of the hash and save it to an array?

The new array should be like this:

@array=["Value1", "Value2", "Value3"]

I've tried this way:

@array=split(/\s\w\(\w\)\,/, $hash{key});

Upvotes: 0

Views: 95

Answers (4)

Ken Williams
Ken Williams

Reputation: 23995

You can do it with a single relatively straightforward regex:

@array = $hash{'key'}[0] =~ m/\s*(\S+)\s+\S+,?/g;

The important thing to know is that with the /g flag, a regex matcher returns all the captured ($1, $2, etc.) groups from matching globally against the string. This regex has one such group.

My assumptions are:

  1. The "Value1", "Value2" parts are just chunks of non-whitespace
  2. The "unit(1)", "unit(2)", parts are also just chunks of non-whitespace

If these aren't valid assumptions, you can replace the two \S+ parts of the regex with something more specific that matches your data.

Upvotes: 0

Chris
Chris

Reputation: 729

And another option:

my %hash = ("key"=>["Value1 unit(1), Value2 unit(2), Value3 unit"]);

my $i;
my @array = grep { ++$i % 2 } split /,?\s/, $hash{key}->[0];

$, = "\n";
print @array;

Upvotes: 1

Kenosis
Kenosis

Reputation: 6204

Here's another option:

use strict;
use warnings;
use Data::Dumper;


my %hash = ("key"=>["1567 I(u), 2070 I(m), 2.456e-2 V(m), 417 ---, 12 R(k),"]);
my @array =  $hash{'key'}->[0] =~ /(\S+)\s+\S+,?/g;
print Dumper \@array;

Output:

$VAR1 = [
          '1567',
          '2070',
          '2.456e-2',
          '417',
          '12'
        ];

Upvotes: 1

Barmar
Barmar

Reputation: 781751

Split the string on comma, then strip off the unit at the end.

map(s/\s.*$//, @array = split(/,\s*/, $hash{'key'}[0]));

Upvotes: 1

Related Questions