简单问题:如何删除字符串中的第n个单词

时间:2011-03-15 07:30:10

标签: regex perl

如何删除字符串中的第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";
}

5 个答案:

答案 0 :(得分:2)

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

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

<强>解释

^         # 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

答案 1 :(得分:2)

print OUT join(' ', splice(split(/ */,$line), 2, 1));

答案 2 :(得分:0)

Mot与正则表达式解决方案一样紧凑但可能更具可读性。

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

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

  return join(" ",@words);
}

答案 3 :(得分: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;

这里的技巧是使用重复运算符。如果$ boolean为true,“$ foo x $ boolean”将保留$ foo,如果为false则将其变为空字符串。

答案 4 :(得分: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