开发者

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

开发者 https://www.devze.com 2023-03-08 03:23 出处:网络
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

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 开发者_如何学Clast 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?


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.


@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"


// 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号