[regexp] How to access the matched result by index?

M

metfan

Hi, gurus,

We know that while using regexp to match something, the matched
result will be set in $1, $2, $3, $4..... but, is there a way to
access the result by an index? for example I've a variable called
$index, if has an integer of 10, so the result I need is $10, so
is there any array for me to use like $MatchedResult[$index]?
thanks so much.
 
G

gnari

metfan said:
Hi, gurus,

We know that while using regexp to match something, the matched
result will be set in $1, $2, $3, $4..... but, is there a way to
access the result by an index? for example I've a variable called
$index, if has an integer of 10, so the result I need is $10, so
is there any array for me to use like $MatchedResult[$index]?
thanks so much.

apart from the $1,$2... thing,

there is the very practical
($a,$b,$c)=/(.)(..)(..)/;

so you can do
@MatchedResult=/$regexp/;
print $MatchedResult[$index];

or just
print (/$regexp/)[$index];

gnari
 
B

Ben Morrow

metfan said:
Hi, gurus,

We know that while using regexp to match something, the matched
result will be set in $1, $2, $3, $4..... but, is there a way to
access the result by an index? for example I've a variable called
$index, if has an integer of 10, so the result I need is $10, so
is there any array for me to use like $MatchedResult[$index]?
thanks so much.

See the example in perldoc perlvar under @-.

Ben
 
D

dw

metfan said:
Hi, gurus,

We know that while using regexp to match something, the matched
result will be set in $1, $2, $3, $4..... but, is there a way to
access the result by an index? for example I've a variable called
$index, if has an integer of 10, so the result I need is $10, so
is there any array for me to use like $MatchedResult[$index]?
thanks so much.

How about using:

$_ = "abcdefghijklmnopqrstuvwxyz";

@MatchedResult = /(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)(\w)/;

for ($count=0; $count<@MatchedResult; $count++) {
print "\$MatchedResult[$count]: $MatchedResult[$count]\n";
}
 
A

Anno Siegel

metfan said:
Hi, gurus,

We know that while using regexp to match something, the matched
result will be set in $1, $2, $3, $4..... but, is there a way to
access the result by an index? for example I've a variable called
$index, if has an integer of 10, so the result I need is $10, so
is there any array for me to use like $MatchedResult[$index]?
thanks so much.

If you know the number of possible matches, the simplest way is

( $1, $2, $3, $4, $5)[ $i];

The simplest isn't necessarily the best way.

Anno
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top