shaneburgess
shaneburgess

Reputation: 15882

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.

Upvotes: 9

Views: 17213

Answers (4)

TLP
TLP

Reputation: 67900

"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};

Upvotes: 1

fbdcw
fbdcw

Reputation: 829

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.

Upvotes: 8

agent-j
agent-j

Reputation: 27913

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;

Upvotes: 2

hexcoder
hexcoder

Reputation: 1220

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

I use the greedy behaviour of .*

Upvotes: 13

Related Questions