2009-02-02 118 views
2

我認爲這會做...如何用Perl正則表達式刪除所有連字符?

$rowfetch = $DBS->{Row}->GetCharValue("meetdays"); 
$rowfetch = /[-]/gi; 
printline($rowfetch); 

但似乎我缺少的正則表達式語法的一個小而關鍵部分。

$rowfetch總是沿着線的東西:

------S 
-M-W--- 
--T-TF- 

等等代表一週的天會議發生

回答

12
$rowfetch =~ s/-//gi 

這就是你需要爲您的第二行有。你只是發現了一些東西,而不是沒有「s」前綴就改變它。

您還需要使用正則表達式運算符「=〜」。

+0

謝謝...那是我的想法...只是不知道如何重新分配它...任何方式做到一行? – CheeseConQueso 2009-02-02 21:10:04

+0

說起來容易做起來比「一行」...我從來沒有找到一種運行正則表達式替換的「純粹」方法。 – user54650 2009-02-02 21:12:02

7

這裏是你的代碼目前所做的:

# Assign 'rowfetch' to the value fetched from: 
#  The function 'GetCharValue' which is a method of: 
#   An Value in A Hash Identified by the key "Row" in: 
#   Either a Hash-Ref or a Blessed Hash-Ref 
#  Where 'GetCharValue' is given the parameter "meetdays" 
$rowfetch = $DBS->{Row}->GetCharValue("meetdays"); 
# Assign $rowfetch to the number of times 
# the default variable ($_) matched the expression /[-]/ 
$rowfetch = /[-]/gi; 
# Print the number of times. 
printline($rowfetch); 

即相當於已經寫了下面的代碼:

$rowfetch = ($_ =~ /[-]/) 
printline($rowfetch); 

你正在尋找的法寶是

=~ 

代幣代替

= 

前者是一個正則表達式運算符,後者是一個賦值運算符。

有許多不同的regex操作符太:

if($subject =~ m/expression/ ){ 
} 

將使給定的代碼塊執行只有$主題定表達式匹配,並且

$subject =~ s/foo/bar/gi 

將取代(s/)所有的實例「 foo「帶」bar「,不區分大小寫(/i),並在變量$subject上多次重複替換(/g)。

4

使用tr運算符比使用s///正則表達式替換要快。

$rowfetch =~ tr/-//d; 

基準:

use Benchmark qw(cmpthese); 

my $s = 'foo-bar-baz-blee-goo-glab-blech'; 

cmpthese(-5, { 
    trd => sub { (my $a = $s) =~ tr/-//d }, 
    sub => sub { (my $a = $s) =~ s/-//g }, 
}); 

我的系統上結果:

  Rate sub trd 
sub 300754/s -- -79% 
trd 1429005/s 375% -- 
1

題外話,但沒有連字符,你怎麼會知道他是 「T」 是星期二或星期四?

相關問題