masterial
masterial

Reputation: 2216

How do I extract data between square brackets that appear several times in a line using perl?

I have a line that containes multiple instances of square bracketed data.

[data 1] junk [data 2] junk,junk [data 3] junk [data 4]

Does any one have a goo regex? So I can use

print $1,$2,$3,$4;

Thanks!

Upvotes: 2

Views: 2813

Answers (3)

DVK
DVK

Reputation: 129403

Use Text::Balanced instead of a regex.

Upvotes: 7

user557597
user557597

Reputation:

If all your looking for is a quick printout, this should do it ..

$s = q( [data 1] junk [data 2] junk,junk [data 3] junk [data 4] );
print join(', ', @{[$s =~ /\[(.*?)\]/g]}), "\n";

Upvotes: 1

cam
cam

Reputation: 14222

my $s = "[data 1] junk [data 2] junk,junk [data 3] junk [data 4]";
my ($one, $two, $three, $four) = $s =~ /\[([^\]]*)\]/g;
print $one, $two, $three, $four;

Upvotes: 4

Related Questions