Welcome, Guest! Registration

loc2log

Thursday, 2024-04-25
Main » 2015 » April » 8 » Perl store regex matches to array
0:13 AM
Perl store regex matches to array

Perl is full of neat one-liners. You can get string regex matches right into an array. It is best shown with example:

To make it interesting let's take some HTML-like markup:

$input='<name="Alice"/><name="Bob"/><name="Eve"/>';

and capture name attribute's values to an array:

@result = $input =~ /(?:\<name=\")(.+?)(?:\"\/>)/g;

As you see the actual capture happens in the middle of regex: "(.+?)", and /g forces the match to repeat over and over.

If we spice up the code with little bit of data dumping:

use Data::Dumper;
print Dumper(\@names);

we'll observe

$VAR1 = [
 'Alice',
 'Bob',
 'Eve'
 ];

Just as required :-)
Views: 641 | Added by: ep | Tags: Perl | Rating: 0.0/0
Total comments: 0
Only registered users can add comments.
[ Registration | Login ]