开发者

Perl search and replace the last character occurrence

I have what I thought would be an easy 开发者_如何学编程problem to solve but I am not able to find the answer to this.

How can I find and replace the last occurrence of a character in a string?

I have a string: GE1/0/1 and I would like it to be: GE1/0:1 <- This can be variable length so no substrings please.

Clarification: I am looking to replace the last / with a : no matter what comes before or after it.


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

I use the greedy behaviour of .*


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 :

(.+)/

So, this Perl script

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

will output :

Result : GE1/0:1

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

Hope this is what you were asking.


This finds a slash and looks ahead to make sure there are no more slashes past it.:

Raw regex:

/(?=[^/]*$)

I think the code would look something like this, but perl isn't my language:

$string =~ s!/(?=[^/]*$)!\:!g;


"last occurrence in a string" is slightly ambiguous. The way I see it, you can mean either:

"Foo: 123, yada: GE1/0/1, Bar: null"

Meaning the last occurrence in the "word" GE1/0/1, or:

"GE1/0/1" 

As a complete string.

In the latter case, it is a rather simple matter, you only have to decide how specific you can be in your regex.

$str =~ s{/(\d+)$}{:$1};

Is perfectly fine, assuming the last character(s) can only be digits.

In the former case, which I don't think you are referring to, but I'll include anyway, you'd need to be much more specific:

$str =~ s{(\byada:\s+\w+/\w+)/(\w+\b)}{$1:$2};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜