2011-03-15 48 views
1

如何删除字符串中的第n个字?
例如我想删除第三个单词;
输入字符串:一二三四五;
输出字符串:一二四五;
简单的问题:如何删除字符串中的第n个字

open (IN, "<$input") or die "Couldn't open input file: $!"; 
open (OUT, ">$output") or die "Couldn't create input file: $!"; 
while (my $line = <IN>) { 
    # line =~ regexp; Dunno what 
    print OUT "$sLine"; 
} 
+0

定义“单词”:是否在单词之前/之后包含标点符号? – 2011-03-15 07:34:27

回答

2
$subject =~ s/^(\s*(?:\S+\s+){2})\S+\s+(.*)$/$1$2/g; 

将删除第三字,其中“字”是连续的非空格字符第三occurence。

说明:

^   # start of string 
(  # Capture the following in backreference $1: 
\s*  # optional whitespace 
(?:  # Match the following group... 
    \S+  # one or more non-space characters 
    \s+  # one or more whitespace characters 
){2}  # ... exactly twice. 
)   # End of capture $1 
\S+\s+ # Match the third word plus following whitespace 
(.*)  # Match and capture the rest of the string 
$   # until the end 
+0

太好了,非常感谢 – ted 2011-03-15 07:50:44

+0

不错的解决方案。这种使用'split'和'join'的解决方案之间的区别在于它保留了每个剩余单词后面的空白_amount_。当然,这是否是好事取决于应用。通过使用\ s它(正确)将所有空白字符(不仅仅是空格)作为分隔符进行计数。 – 2011-03-15 15:17:44

0

蒙特一样紧凑正则表达式溶液但可能更具有可读性。

sub delete_nth 
{ 
    my $n = shift; 
    my $text = shift; 

    my @words = split(/ /,$text); 
    delete $words[$n-1]; 

    return join(" ",@words); 
} 
+0

来自[perldoc.perl.com](http://perldoc.perl.org/functions/delete.html):_请注意,对数组值的调用delete已被弃用,并且可能会在未来版本的Perl中被删除._ – 2011-03-15 07:42:14

2
print OUT join(' ', splice(split(/ */,$line), 2, 1)); 
0
my $x = "one two three four five six seven"; 

my $nth = 4; 
my $i; 

$x =~ s/(\b\S+\s*)/ $1 x (++$i != $nth) /eg; 

print $x; 

这里的技巧是使用重复操作符的。 “$ foo x $ boolean”会在$ boolean为true的情况下按原样离开$ foo,如果它为false,它会将其变为空字符串。

0

为了回应@Ted Hopp的评论,我决定看看我是否可以在保留空白的同时做到这一点。我还对如何处理删除的单词之前和之后的空白做出了条件。是的,这是过度杀伤力,但我拖延做其他事情。

#!/usr/bin/perl 

use strict; 
use warnings; 

my $word_to_remove = 3; 
my $remove_leading_space = 0; 
my $remove_trailing_space = 1; 

while(my $in_string = <DATA>) { 
    chomp $in_string; 

    my @fields = split(/(\s+)/, $in_string); 

    my $field_to_remove = 2*$word_to_remove - 2; 
    #back up the splice position if removing leading space 
    $field_to_remove -= ($remove_leading_space) ? 1 : 0; 
    #move forward if there are is a leading portion of whitespace 
    $field_to_remove += ($fields[0] eq '') ? 2 : 0; 

    my $total_to_remove = 
    1 + 
    (($remove_leading_space) ? 1 : 0) + 
    (($remove_trailing_space) ? 1 : 0); 

    splice(@fields, $field_to_remove, $total_to_remove); 
    my $out_string = join('', @fields); 
    print $out_string . "\n"; 
} 

__DATA__ 
one two four five 
one two four five 
    one two four five 
相关问题