Simple Question: How to delete n-th word in a string
How to delete n-th word in a string?
e.g. I'd like to delete 3rd word; input string:开发者_高级运维 one two three four five; output string: one two four five;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";
}
$subject =~ s/^(\s*(?:\S+\s+){2})\S+\s+(.*)$/$1$2/g;
will remove the third word where "word" is the third occurence of contiguous non-space characters.
Explanation:
^ # 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
print OUT join(' ', splice(split(/ */,$line), 2, 1));
Mot as compact as the regex solution but possibly more readable.
sub delete_nth
{
my $n = shift;
my $text = shift;
my @words = split(/ /,$text );
delete $words[$n-1];
return join(" ",@words);
}
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;
The trick here is the use of the repetition operator. "$foo x $boolean" will leave $foo as-is if $boolean is true, and will turn it into an empty string if it's false.
In response to the comments by @Ted Hopp I decided to see if I could do this while preserving whitespace. I also made conditional on how to deal with the whitespace before and after the removed word. Yes it is overkill but I am procrastinating on doing something else.
#!/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
精彩评论