get the matching regex pattern

R

Ram Prasad

I have a somewhat strange requirement
I want to find if a regex matched what exactly matched

to reproduce this

------------------
my @x;
$x[0] = 'chi+ld*';
$x[1] = '\sjoke';

$_=getinput(); # for test assume $_="This is a joke";

if(/($x[0]|$x[1])/){
print "Matched '$1' \n";
}
-----------------


I want to know if $x[0] matched or $x[1] matched
What is the most efficient way of doing this ?


Thanks
Ram
 
C

comp.llang.perl.moderated

I have a somewhat strange requirement
I want to find if a regex matched what exactly matched

to reproduce this

------------------
my @x;
$x[0] = 'chi+ld*';
$x[1] = '\sjoke';

$_=getinput(); # for test assume $_="This is a joke";

if(/($x[0]|$x[1])/){
print "Matched '$1' \n";}

One way:

if ( / ($x[0]) | ($x[1]) /x ) {
print defined $1 ? "first" : "second";
}

But, this may be more efficient often:

if ( /$x[0]/ ) { print "first" }
elsif ( /$x[1]/) { print "second" }

Ordering alternatives with the most likely
matches in front can greatly increase efficiency
too.
 
G

Gunnar Hjalmarsson

Ram said:
I have a somewhat strange requirement
...

You had posted the same question to the beginners mailing list just a
few minutes before you posted here, and I just spent a few minutes
answering the question there without knowing that you already had been
helped here.

DO NEVER DO THAT AGAIN !!!
 

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,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top