如何使用Perl将冒号放入字符串中最后两个字符?

时间:2020-12-28 21:45:16

I'm trying to find a way to place a colon ( : ) into a string, two characters from the end of the string.

我试图找到一种方法将冒号(:)放入一个字符串中,字符串末尾有两个字符。

Examples of $meetdays:
1200 => 12:00
900 => 9:00
1340 =>13:40

$ meetdays的例子:1200 => 12:00 900 => 9:00 1340 => 13:40

Not sure if this should be a regular expression or just another function that I'm not aware of.

不确定这应该是正则表达式还是我不知道的另一个函数。

5 个解决方案

#1


s/(?=..$)/:/

Don't use roe's suggestion of $&. perldoc perlvar:

不要使用roe的$&的建议。 perldoc perlvar:

The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. See "BUGS".

在程序中的任何位置使用此变量会对所有正则表达式匹配造成相当大的性能损失。见“BUGS”。

#2


Can also use substr() as well.....

也可以使用substr()......

my $string = "1200";
substr $string, -2, 0, ':';

# $string => '12:00';

#3


You could try this:

你可以试试这个:

s/..$/:$&/

it matches two-characters at the end of the string, and replaces it with a colon, and the matched string (i.e. the two characters).

它匹配字符串末尾的两个字符,并用冒号和匹配的字符串(即两个字符)替换它。

EDIT
Fixed sed-backref to the perl equivalent.

编辑修复了perl等效的sed-backref。

#4


roe's answer "works" , but its rather inobvious regex.

罗的答案“有效”,但其相当不明显的正则表达式。

I would more go for

我会更加努力

s/(^.*)(..$)/$1:$2/

Because I just love backrefs.

因为我喜欢backrefs。

Its overkill for what you're doing, but to me its more semantically expressive.

它对你正在做的事情有些过分,但对我来说它更具有语义表现力。

#5


The Perl equivalent of sed's & is $&, so it should be:

Perl相当于sed的&是$,所以它应该是:

 $s = s /..$/:$&/s;

#1


s/(?=..$)/:/

Don't use roe's suggestion of $&. perldoc perlvar:

不要使用roe的$&的建议。 perldoc perlvar:

The use of this variable anywhere in a program imposes a considerable performance penalty on all regular expression matches. See "BUGS".

在程序中的任何位置使用此变量会对所有正则表达式匹配造成相当大的性能损失。见“BUGS”。

#2


Can also use substr() as well.....

也可以使用substr()......

my $string = "1200";
substr $string, -2, 0, ':';

# $string => '12:00';

#3


You could try this:

你可以试试这个:

s/..$/:$&/

it matches two-characters at the end of the string, and replaces it with a colon, and the matched string (i.e. the two characters).

它匹配字符串末尾的两个字符,并用冒号和匹配的字符串(即两个字符)替换它。

EDIT
Fixed sed-backref to the perl equivalent.

编辑修复了perl等效的sed-backref。

#4


roe's answer "works" , but its rather inobvious regex.

罗的答案“有效”,但其相当不明显的正则表达式。

I would more go for

我会更加努力

s/(^.*)(..$)/$1:$2/

Because I just love backrefs.

因为我喜欢backrefs。

Its overkill for what you're doing, but to me its more semantically expressive.

它对你正在做的事情有些过分,但对我来说它更具有语义表现力。

#5


The Perl equivalent of sed's & is $&, so it should be:

Perl相当于sed的&是$,所以它应该是:

 $s = s /..$/:$&/s;