Perl 用新单词替换许多单词
我有以下字符串: 猫狗狐狸猫熊狐狸 我需要把这句话中的猫和狐狸换成动物 我做了以下工作:Perl 用新单词替换许多单词,perl,replace,Perl,Replace,我有以下字符串: 猫狗狐狸猫熊狐狸 我需要把这句话中的猫和狐狸换成动物 我做了以下工作: $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/
$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";
}
但是word的Catepiller和foxy partscat和fox也被替换的问题。
如何只替换单词cat和fox
$line =~ s/\b(?:$Str1|$Str2)\b/$NewStr/g;
这些变化意味着什么:
\b字边界的零宽度断言
?:启动一个组,但不要将其用于捕获,而是分组
这些变化意味着什么:
\b字边界的零宽度断言
?:启动一个组,但不要将其用于捕获,只需分组使用单词边界断言来构建正则表达式。有关它的信息,请访问。使用单词边界断言来构建正则表达式。您可以在上找到相关信息。这里还有几个问题
# 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;
这里还有几个问题
# 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;
谢谢它可以工作:。但如果我在括号里有一些词。比如说我有一个像这只狐狸一样的狐狸词。我有一个结果-带括号的动物。替换word时如何删除括号?谢谢。它可以工作:。但如果我在括号里有一些词。比如说我有一个像这只狐狸一样的狐狸词。我有一个结果-带括号的动物。替换word时如何删除括号?谢谢。它可以工作:。但如果我在括号里有一些词。比如说,我有狐狸这个词,就像这只狐狸。我有一个结果-带括号的动物。替换word时如何删除括号?-我建议您接受这个答案或Vorspring的答案,如果您更喜欢这个答案,并就这个新问题提出一个新问题。@JackPerl只能有一个:@JackPerl最简单的方法是在删除parens之后立即添加另一个正则表达式。谢谢。它可以工作:。但如果我在括号里有一些词。比如说,我有狐狸这个词,就像这只狐狸。我有一个结果-带括号的动物。替换word时如何删除括号?-我建议您接受这个答案或Vorspring的答案,如果您更喜欢这个答案,并就这个新问题提出一个新问题。@JackPerl只能有一个:@JackPerl最简单的方法是在删除paren之后立即添加另一个正则表达式。