用一个新词替换许多词 [英] replace many words with a new one
本文介绍了用一个新词替换许多词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串:
猫狗狐狸毛毛虫熊狐狸
我需要将这句话中的cat"和fox"词替换为animal"一词
I need to replace "cat" and "fox" words from this sentence to word "animal"
我执行以下操作:
$Str1="cat";
$Str2="fox";
$NewStr="animal";
open(F1, "<$inputFile") or die "Error: $!";
open(F2, ">$outputFile") or die "Error: $!";
while ($line = <F1>) {
$line =~ s/$Str1|$Str2/NewStr/g;
print F2 "$line";
}
但是单词的毛毛虫"和狡猾"部分(猫"和狐狸")也被替换的问题.如何只替换单词cat"和fox"?
But the problem that word's "catepillar" and "foxy" parts("cat" and fox) also are replaced. How to replace only words "cat" and "fox"?
推荐答案
这里还有几个问题.
# First, always use strict and warnings
# This will save you tons
use warnings;
use strict;
# declare your vars with 'my' for lexical scope
my $inputFile = "somefile";
my $outputFile = "someotherfile";
my $Str1="cat";
my $Str2="fox";
my $NewStr="animal";
# use 3-arg lexically scoped open
open(my $F1, "<", $inputFile) or die "Error: $!";
open(my $F2, ">", $outputFile) or die "Error: $!";
while (my $line = <$F1>) {
# surround with word boundary '\b'
# NewStr is missing the "$"
$line =~ s/\b(?:$Str1|$Str2)\b/$NewStr/g;
# UPDATED
# this should work to remove the parens
$line =~ s/(\($NewStr\))/$NewStr/g;
print $F2 "$line";
}
# close your file handles
close $F1;
close $F2;
这篇关于用一个新词替换许多词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文