Perl searches and replaces the last occurrence of a character

I have something that I thought would be an easy problem to solve, but I can not find the answer to this question.

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

I have a line: GE1 / 0/1, and I would like it to be: GE1 / 0: 1 <- This can be a variable length, so substrings are not required.

Explanation: I want to replace the latter / with: no matter what happens before or after it.

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

I use greedy behavior .*

+11
source

I may not understand the variable length problem, but I would do the following:

You can combine what you want with a regular expression:

 (.+)/ 

So this Perl script

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

will output:

 Result : GE1/0:1 

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

Hope this is what you asked for.

+4
source

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

Raw regular expression:

 /(?=[^/]*$) 

I think the code will look something like this, but perl is not my language:

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

"Last occurrence in a line" is a bit ambiguous. The way I see it can mean either:

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

The meaning of the last occurrence in the "word" GE1 / 0/1 or:

 "GE1/0/1" 

Like a complete line.

In the latter case, this is a fairly simple question, you only need to decide how specific you can be in your regular expression.

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

It is perfectly normal if the last character (s) can only be numbers.

In the first case, which I do not think you mean, but I will include it anyway, you need to be more specific:

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

Source: https://habr.com/ru/post/891720/


All Articles