Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 445
Pradeesh Avatar asked May 23 '11 04:05

Pradeesh


People also ask

How do I remove a character from a string in Perl?

The chop() function in Perl is used to remove the last character from the input string.

How do I remove the last word from a string in Perl?

We can use the chop() method to remove the last character of a string in Perl. This method removes the last character present in a string. It returns the character that is removed from the string, as the return value.

How do you find the length of a string in Perl?

length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Return: Returns the size of the string.

How do I concatenate in Perl?

Concatenate strings by inserting a fullstop (.) operator between them. Perl will automatically 'stringify' scalar variables that were initialised as a number.


2 Answers

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.

like image 161
Tim Avatar answered Oct 14 '22 04:10

Tim


@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"
like image 42
maerics Avatar answered Oct 14 '22 04:10

maerics