4

我有变量$pos和。我想从这个字符串中删除position 。$toRemove$line$toRemove$pos

$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30; # the 3rd 'kitty'

我想检查位置 30 是否有字符串kitty,我想删除这个字符串。

你能给我一个解决方案吗?我可以使用很多循环和变量来做到这一点,但它看起来很奇怪,而且工作起来很慢。

4

5 回答 5

6
if (substr($line, $pos, length($toRemove)) eq $toRemove) {
    substr($line, $pos, length($toRemove)) = "";
}
于 2012-08-10T09:20:32.510 回答
3
$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30; # the 3rd 'kitty'

pos($line) = $pos;
$line =~ s/\G$toRemove//gc;
print $line;

输出:

Hello kitty how are you kitty  nice kitty
于 2012-08-10T09:21:55.553 回答
2
$line =~ s/^.{30}\K$toRemove//;

这使用后向断言来匹配前 30 个字符,而不将它们包含在被替换的模式部分中。

于 2012-08-10T10:14:25.627 回答
2

还有一种方式:

$line = "Hello kitty how are you kitty kitty nice kitty";
$toRemove = "kitty";
$pos = 30;

$line =~ s/(.{$pos})$toRemove/$1/;
print $line;

结果:

Hello kitty how are you kitty  nice kitty
于 2012-08-10T09:25:22.523 回答
1

The [pos][pos] operator is an lvalue for just this sort of thing:

[pos]:

use strict;
use warnings;

my $line = "Hello kitty how are you kitty kitty nice kitty";
my $toRemove = "kitty";
my $pos = 30;

pos($line) = $pos;

$line =~ s/\G$toRemove//;

print $line;

output

Hello kitty how are you kitty  nice kitty
于 2012-08-12T02:40:01.933 回答