2015-02-24 108 views
0

我已經創建了一個函數來解析命令的輸出。用於解析命令輸出的正則表達式

的命令的輸出將是以下:

Host-profile-count User  114 

(注:號碼114是不constant.it可以是任何正數> = 0)

現在我只需要在號碼(在這種情況下是114)被返回。 我想我的腳本中的正則表達式是錯誤的。當我運行腳本,我得到的輸出爲0.它應該是114. 有人可以幫助我與正則表達式嗎?

sub _count { 

    my ($self) = @_; 
    my $cmd = 'command goes here '; 
    my $profiles = 0; 

    $self->execute($cmd); 

    foreach my $line (@{ $self->get_stdout() }) { 
     if ($line =~ m/Host\sprofile\scount\s+\S*\s+(\S*)/msx) { 
      $profiles = $1; 
     } 
    } 

    $profiles =~ s/^\s+|\s+$//msxg; 
    return $profiles; 
} 
+1

將單詞之間的'\ s's更改爲連字符,並且工作正常。你也不需要這些修飾符。 – hwnd 2015-02-24 02:44:46

+2

除非你需要檢查是否存在Host-profile-count(這可能會更好地單獨完成),我只會去'我的($ profiles)= $ line =〜/(\ d +)/'哪個找到第一個數字序列並將其分配給'$ profiles'。你不應該爲你寫的每一個正則表達式添加'/ msx' - 這會浪費你的代碼讀者難以理解的原因。 – Borodin 2015-02-24 03:10:19

回答

0

是的,你WRONLY置於其之間匹配\s它匹配任何空格字符),而不是連字符..

m/Host-profile-count\s+\S*\s+(\S*)/msx 

DEMO

添加一個字邊界\b如果必要的話,在Host之前的字詞字符和非字詞字符)。

+0

boundary \ b?你可以向我解釋爲什麼這是必需的嗎? – user3587025 2015-02-24 02:48:32

+0

沒有'\ b',上面的正則表達式也會在'foobarHost-profile-count User 114'中找到一個匹配。 '\ bHost-profile-count \ s + \ S * \ s +(\ S *)'不會像上面那樣做。 – 2015-02-24 02:50:30

+0

好的,謝謝你的解釋。 – user3587025 2015-02-24 02:52:49