How to remove last n number of numeric characters from a string in perl

13,853

Solution 1

A regex substitution for removing the last digits:

my $str = '/iwmout/sourcelayer/iwm_service/iwm_ear_layer/pomoeron.xml@@/main/lsr_int_vnl46a/61';
$str =~ s/\d+$//;

\d+ matches a series of digits, and $ matches the end of the line. They are replaced with the empty string.

Solution 2

@Tim's answer of $str =~ s/\d+$// is right on; however, if you wanted to strip the last n digit characters of a string but not necessarily all of the trailing digit characters you could do something like this:

my $s = "abc123456";
my $n = 3; # Just the last 3 chars.
$s =~ s/\d{$n}$//; # $s == "abc123"
Share:
13,853
Admin
Author by

Admin

Updated on June 08, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a situation where I need to remove the last n numeric characters after a / character.

    For eg:

    /iwmout/sourcelayer/iwm_service/iwm_ear_layer/pomoeron.xml@@/main/lsr_int_vnl46a/61
    

    After the last /, I need the number 61 stripped out of the line so that the output is,

    /iwmout/sourcelayer/iwm_service/iwm_ear_layer/pomoeron.xml@@/main/lsr_int_vnl46a/
    

    I tried using chop, but it removes only the last character, ie. 1, in the above example.

    The last part, ie 61, above can be anything, like 221 or 2 or 100 anything. I need to strip out the last numeric characters after the /. Is it possible in Perl?

  • Tim
    Tim almost 13 years
    Although this answers the question title, it does not answer what Pradeesh actually asked :)
  • Admin
    Admin almost 13 years
    Thank You very much for the replies. My problem there was that i am not sure what exactly the value of "n" is. It keeps changing as i am reading line by line from a file. Tim's Answer did the trick :).
  • Joel Berger
    Joel Berger almost 13 years
    @Pradeesh, if this answer worked for you, please mark it "Correct" by selecting the check mark
  • maerics
    maerics almost 13 years
    @Tim: yes - that's why I started my answer with a nod to yours =)