【问题标题】:Replacing many words in brackets with a new one用一个新词替换括号中的许多词
【发布时间】:2013-05-17 20:59:21
【问题描述】:

我有以下字符串:

猫狗(狐狸)毛毛虫熊狐狸

我需要把这句话中的“cat”和“fox”替换成“animal”

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;
     print $F2 "$line";

}

# close your file handles
close $F1;
close $F2;

没关系,但是如果我在括号“()”中有一些词。假设我有 “像这样的狐狸(狐狸)。 我有结果 - 带括号的“(动物)”。替换word时如何去掉括号?

【问题讨论】:

标签: string perl replace


【解决方案1】:
s/\(?\b(?:cat|fox)\b\)?/animal/g;

【讨论】:

    【解决方案2】:

    @tripleee 是正确的。让它变得超级简单:

    $line =~ s/\(?\b(?:$Str1|$Str2)\b\)?/$NewStr/g;
    

    请注意,由于大写,因此您在 Cat 上方发布的代码不会被选中。

    【讨论】:

    • 作为评论可能会更好。
    猜你喜欢
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多