Reputation: 15481
In my perl program, I am having a string in $new
which is of variable length. Following are some of the instances:
$new = "sdf / wer / wewe / dfg";
$new = "lkjz / dfgr / wdvf";
$new = "asdfe";
How do I extract the elements seperated by /
into an array using Regex?
Upvotes: 1
Views: 123
Reputation: 126722
You don't say what characters can be in the elements, but assuming they can contain anything but slashes, this will extract them for you. It also excludes any leading or trailing whitespace and empty fields.
use strict;
use warnings;
my @new = (
" sdf / wer / wewe / dfg ",
" sdf / dfgr / wdvf ",
" asdfe ",
" first field / second field ",
" a / b / c / d / e / f ",
);
for (@new) {
my @fields = m|[^/\s](?:[^/]*[^/\s])?|g;
printf "(%s)\n", join ', ', map "'$_'", @fields;
}
output
('sdf', 'wer', 'wewe', 'dfg')
('sdf', 'dfgr', 'wdvf')
('asdfe')
('first field', 'second field')
('a', 'b', 'c', 'd', 'e', 'f')
Upvotes: 2
Reputation: 61515
You can use the split
function, which takes as arguments a pattern to split on, the string to split, and optionally the number of times to split.
$new = "sdf / wer / wewe / dfg";
@values = split(" / ", $new );
Upvotes: 3
Reputation: 64909
If you have a fixed delimiter, then a regex isn't necessarily the best option. The split function is a better choice:
my @items = split " / ", $new;
Upvotes: 2