Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

i am new in perl. the regexp/pattern matching seems very strange to me.
I need to do pattern matching and i can't get the correct output.
Here's what im trying to do.
i have a variable $callerid.Let's say my variable $callerid obtained the value 0921234567, what i want to get is just the last 7 characters of $callerid(which is 1234567). how will i do that in perl? please help. thanks

Edited 2002-04-04 by mirod: changed title

  • Comment on Get last 7 characters with regexp (was: PLEASE HELP!!! REGEXP)

Replies are listed 'Best First'.
Re: PLEASE HELP!!! REGEXP
by Chmrr (Vicar) on Apr 04, 2002 at 06:10 UTC

    You're probably better off using good ole' substr instead. It's built for doing such things.

    If you really want to use a regex for some perverse reason -- well, then you're stark raving mad. But in good company. Anyways, think on the following:

    EnglishRegex translation
    We want to match..$callerid =~ /
    ..and remember..(
    ..any character...
    ..7 times..{7}
    ..stop remembering..)
    ..then the end of line..$
    ..and that's the end of the match./;

    Putting that all together, we would get $callerid =~ /(.{7})$/; which would leave the last seven digits in $1. I will reiterate that you don't want to do this, though. It's slow and ugly; use substr. The above was provided as a learning exercise.

    Share and enjoy. :)

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

      You can code exactly like that in Perl, thanks to the /x modifier. It allows you to insert comments inside the regexp.
      $callerid =~ / # we want to match
                   ( # and remember
                   . # any character
                 {7} # 7 times
                   ) # stop remembering
                   $ # then the end of line
                   /x; # and that's the end of the match
      
      In this particular case, this is overkill, but in some cases, it can be very useful in more cmoplicated situations.

      And as all others in this thread have said, I too recommend using substr.

Re: PLEASE HELP!!! REGEXP
by tachyon (Chancellor) on Apr 04, 2002 at 06:05 UTC

    All you need is substr

    $callerid = '12345678901234567'; $last_bit = substr $callerid, -7; print $last_bit;

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: PLEASE HELP!!! REGEXP
by ariels (Curate) on Apr 04, 2002 at 06:05 UTC

    Use substr: $se7en = substr $callerid, -7.

    If you really insist, you could say ($se7en) = ($callerid =~ /(.{7})$/);. But you really want to use a regexp only if you want to validate $callerid at the same time (for instance, to ensure the last 7 characters really are digits). To do that, you'll have to read perlre.