Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 583
shaneburgess Avatar asked Jun 30 '11 13:06

shaneburgess


3 Answers

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

I use the greedy behaviour of .*

like image 120
hexcoder Avatar answered Nov 03 '22 09:11

hexcoder


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.

like image 20
fbdcw Avatar answered Nov 03 '22 10:11

fbdcw


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;
like image 42
agent-j Avatar answered Nov 03 '22 11:11

agent-j