2012-08-10 127 views
4

我有變量$pos,$toRemove$line。我想從$pos位置刪除此字符串$toRemove如何從某個位置的字符串中刪除字符?

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

我要檢查,如果從30位有串kitty,我想正是刪除此一個。

你能給我一個解決方案嗎?我可以使用大量的循環和變量,但它看起來很奇怪,而且工作非常慢。

回答

5
if (substr($line, $pos, length($toRemove)) eq $toRemove) { 
    substr($line, $pos, length($toRemove)) = ""; 
} 
+2

Perl中,你可以多年後仍然學習有趣的語法... – naden 2012-08-10 10:00:26

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 
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 
2
$line =~ s/^.{30}\K$toRemove//; 

這將使用一個後置斷言來匹配前30個字符,而不會將其包含在替換的模式部分中。

1

的[pos] [POS]運營商是一個左值只是這樣的事情:

[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; 

輸出

Hello kitty how are you kitty nice kitty 
相關問題