basic regex back reference

G

gcr

Newbie alert. Thanks for any help.

Can't get back references - I want to pull the bracketed numbers (and
put them in an array)

#!/usr/bin/perl

use warnings;
use strict;

my $output = "5[64]790[908]90567[5678]101";
$output =~ m/(\[+[*\d]+\])/g;
print "$1\n";

prints [64]

was hoping to find [908] in $2 and [5678] in $3 ...
 
J

Josef Moellers

gcr said:
Newbie alert. Thanks for any help.

Can't get back references - I want to pull the bracketed numbers (and
put them in an array)

#!/usr/bin/perl

use warnings;
use strict;

my $output = "5[64]790[908]90567[5678]101";
$output =~ m/(\[+[*\d]+\])/g;
print "$1\n";

prints [64]

was hoping to find [908] in $2 and [5678] in $3 ...

You can use a while loop to pull out subsequent matches (dunno if
there's a proper word for that):

use warnings;
use strict;
my @array;
my $output = "5[64]790[908]90567[5678]101";
while ($output =~ m/(\[+[*\d]+\])/g) {
push @array, $1;
}
print join(",", @array), "\n";

This will print
[64],[908],[5678]
 
G

gcr

Aukjan van Belkum said:
my @array = ($output =~ m/(\[+[*\d]+\])/g);

works great! thanks!
(I still don't understand but the pain is gone)

The original only matches once(?)
and/or I'm not understanding the $1 $2 functionality(?)

Thanks again!
 
D

Dr.Ruud

gcr schreef:
/(\[+[*\d]+\])/

The "\[+" means: one or more literal "["s.

The "[*\d]" is a character class off a literal asterisk and a digit, so
it tries to match either an asterisk or a digit. The "+" behoind it
means "one or more of the previous" again.

ITYM: /(\[\d+\])/
which means: a literal "[", followed by one or more digits, followed by
a literal "]".
 
J

John W. Krahn

gcr said:
Aukjan van Belkum said:
my @array = ($output =~ m/(\[+[*\d]+\])/g);

works great! thanks!
(I still don't understand but the pain is gone)

The original only matches once(?)
and/or I'm not understanding the $1 $2 functionality(?)

$1 contains the match in the first set of parentheses and $2 contains the
match in the second set of parentheses. You only have one set of parentheses
in that pattern.


John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top