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

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

For instance,

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

After the last / I need the number 61 to be removed from 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 only removes the last character, i.e. 1, in the above example.

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

+4
source share
3 answers

Replacing regular expressions to remove 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 a line. They are replaced by an empty string.

+7
source

@ The answer to the question $str =~ s/\d+$// correct; however, if you want to delete the last n digits of a line character, but not necessarily all the digits at the end, you can do something like this:

 my $s = "abc123456"; my $n = 3; # Just the last 3 chars. $s =~ s/\d{$n}$//; # $s == "abc123" 
+7
source
 // Code to remove last n number of strings from a string. // Import common lang jar import org.apache.commons.lang3.StringUtils; public class Hello { public static void main(String[] args) { String str = "Hello World"; System.out.println(StringUtils.removeEnd(str, "ld")); } } 
0
source

All Articles