perl 字符串删除末尾几个字符_如何從perl中的字符串中刪除最后n個數字字符

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

我有一種情況,我需要刪除/字符后的最后n個數字字符。

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,

在最后一個/之后,我需要從行中剝離出數字61,以便輸出為,

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

我嘗試使用chop,但它只刪除了最后一個字符,即。 1,在上面的例子中。

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?

上面的最后一部分,即61,可以是任何東西,比如221或2或100。我需要在/后刪除最后的數字字符。 Perl有可能嗎?

3 个解决方案

#1

7

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.

\ d +匹配一系列數字,$匹配行尾。它們被空字符串替換。

#2

7

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

@Tim對$ str = ~s / \ d + $ //的回答是正確的;但是,如果要刪除字符串的最后n位數字符,但不一定要刪除所有字符數字字符,則可以執行以下操作:

my $s = "abc123456";

my $n = 3; # Just the last 3 chars.

$s =~ s/\d{$n}$//; # $s == "abc123"

#3

0

// 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"));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值