get the matching regex pattern

Discussion in 'Perl Misc' started by Ram Prasad, Mar 20, 2008.

  1. Ram  Prasad

    Ram Prasad Guest

    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



    --
    For spammers only

    http://pragatee.com
    Ram Prasad, Mar 20, 2008
    #1
    1. Advertising

  2. On Mar 20, 6:16 am, Ram Prasad <> wrote:
    > 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 ?
    >


    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.

    --
    Charles DeRykus
    comp.llang.perl.moderated, Mar 20, 2008
    #2
    1. Advertising

  3. Ram Prasad wrote:
    > 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 !!!

    --
    Gunnar Hjalmarsson
    Email: http://www.gunnar.cc/cgi-bin/contact.pl
    Gunnar Hjalmarsson, Mar 20, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xah Lee
    Replies:
    1
    Views:
    923
    Ilias Lazaridis
    Sep 22, 2006
  2. Xah Lee
    Replies:
    8
    Views:
    451
    Ilias Lazaridis
    Sep 26, 2006
  3. Marc Bissonnette

    Pattern matching : not matching problem

    Marc Bissonnette, Jan 8, 2004, in forum: Perl Misc
    Replies:
    9
    Views:
    216
    Marc Bissonnette
    Jan 13, 2004
  4. Xah Lee
    Replies:
    2
    Views:
    205
    Xah Lee
    Sep 25, 2006
  5. Replies:
    2
    Views:
    378
Loading...

Share This Page