0

好的,我得到了一个相当简单的(至少看起来很简单)。我有一个多行字符串,我只是在用其他东西替换不同的单词。让我演示给你看...

#!/usr/bin/perl -w
use strict;

$_ = "That is my coat.\nCoats are very expensive.";
s/coat/Hat/igm;
print;

输出将是
That is my Hat
Hats are very expensive...

第一行的“帽子”不应该大写。是否有任何技巧可以使外壳符合英语的书写方式?谢谢 :)

4

4 回答 4

5

看看如何替换字符串和保留它的大写小写

有关更多详细信息,请参阅如何在 LHS 上不区分大小写地替换,同时在 RHS 上保留大小写?

于 2010-08-12T08:07:28.320 回答
4

您可以使用e修饰符来s///做到这一点:

s/(coat)/ucfirst($1) eq $1 ? 'Hat' : 'hat'/igme;
于 2010-08-12T07:56:37.497 回答
1

一方面,您应该使用\b(word boundary) 来匹配整个单词。例如s/hat/coat/将更That改为Tcoat不带前导\b。现在回答你的问题。使用该标志/e,您可以在正则表达式的替换部分中使用 Perl 代码。因此,您可以编写一个 Perl 函数来检查匹配的大小写,然后正确设置替换的大小写:

my $s = "That is my coat.\nCoats are very expensive.";
$s =~ s/(\bcoat)/&same_case($1, "hat")/igme;
print $s, "\n";

sub same_case {
        my ($match, $replacement) = @_;

        # if match starts with uppercase character, apply ucfirst to replacement
        if($match =~ /^[A-Z]/) {
                return ucfirst($replacement);
        }
        else {
                return $replacement;
        }
}

印刷:

That is my hat.
Hats are very expensive.
于 2010-08-12T07:56:20.643 回答
0

这可能会解决您的问题:


#!/usr/bin/perl -w

use strict;

sub smartSubstitute {
    my $target = shift;
    my $pattern = shift;
    my $replacement = shift;

    $pattern = ucfirst $pattern;
    $replacement = ucfirst $replacement;

    $target =~ s/$pattern/$replacement/gm;

    $pattern = lcfirst $pattern;
    $replacement = lcfirst $replacement;

    $target =~ s/$pattern/$replacement/gm;

    return $target;
}

my $x = "That is my coat.\nCoats are very expansive.";
my $y = smartSubstitute($x, "coat", "Hat");
print $y, "\n";
于 2010-08-12T08:16:06.997 回答