2010-08-12 67 views
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...

在第一行的「帽子」不應該大寫。是否有任何技巧可以使外殼符合英語的寫法?謝謝:)

+0

我想你是不是在油漆和塗料行業的工作? :) – 2010-08-12 07:49:23

+0

首先,不要使用修飾符我,如果你想區分大小寫。 – 2010-08-12 07:55:28

+0

您需要定義您的範圍。你打算在*很多詞上使用這個詞嗎? – Zaid 2010-08-12 07:59:18

回答

1

首先,你應該使用\b(字邊界)只匹配整個單詞。例如,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. 
4

可以使用e修飾符s///做訣竅:

s/(coat)/ucfirst($1) eq $1 ? 'Hat' : 'hat'/igme; 
+1

不是一個完整的解決方案,但它涵蓋'大衣'和'帽子' – Axeman 2010-08-12 13:05:23

+0

聰明的解決方案! – David 2010-08-14 09:12:50

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"; 
相關問題