Perl搜索并替换最后一个字符

sha*_*ess 8 regex perl replace

我有我认为容易解决的问题,但我无法找到答案.

如何找到并替换字符串中最后一个字符?

我有一个字符串:GE1/0/1我希望它是:GE1/0:1 < - 这可以是可变长度所以请不要有子串.

澄清: 我正在寻找替换最后一个/与:无论在它之前或之后发生什么.

hex*_*der 12

use strict;
use warnings;
my $a = 'GE1/0/1';
(my $b = $a) =~ s{(.*)/}{$1:}xms;
print "$b\n";
Run Code Online (Sandbox Code Playgroud)

我使用贪婪的行为 .*


fbd*_*dcw 6

Perhaps I have not understand the problem with variable length, but I would do the following :

You can match what you want with the regex :

(.+)/
Run Code Online (Sandbox Code Playgroud)

So, this Perl script

my $text = 'GE1/0/1';
$text =~ s|(.+)/|$1:|;
print 'Result : '.$text;
Run Code Online (Sandbox Code Playgroud)

will output :

Result : GE1/0:1
Run Code Online (Sandbox Code Playgroud)

The '+' quantifier being 'greedy' by default, it will match only the last slash character.

希望这就是你要的。