简体   繁体   English

Perl 搜索并替换最后出现的字符

[英]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.我有一个字符串:GE1/0/1,我希望它是:GE1/0:1 <- 这可以是可变长度,所以请不要使用子字符串。

Clarification: I am looking to replace the last / with a: no matter what comes before or after it.澄清:我希望用 a: 替换最后一个 / ,无论它之前或之后是什么。

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所以,这个 Perl 脚本

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

will output:将 output:

Result : GE1/0:1

The '+' quantifier being 'greedy' by default, it will match only the last slash character. '+' 量词默认为'greedy',它将仅匹配最后一个斜杠字符。

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:我认为代码看起来像这样,但 perl 不是我的语言:

$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 中的最后一次出现,或者:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM