2011-04-13 38 views
2

我有幾個條件存儲在變量$ conditions下的字符串中。該字符串會是這個樣子如何從Perl中的較大字符串中獲取字符串

"s(job_name1) or s(job_name2) or s(job_name3) and s(job_name4)" 

我想什麼做的只是讓每個作業名稱,不可把它在一個臨時變量。現在我有以下幾點,但是我的直覺告訴我說那不行。

@temp = split(/(s()\ orand)/, $conditions) 

有關如何做到這一點的任何想法?

+0

這功課嗎?如果是這樣,請標記爲這樣。 – 2011-04-13 16:49:23

+2

不是這不是作業,我只是教我自己perl – Brandon 2011-04-13 17:02:18

回答

2

這是微不足道的:

my @names = $conditions =~ /s\(([^)]*)\)/g; 

這種簡單的解決方案假設括號內的文字不能包含一個括號,像逃避,沒有什麼是可能的。

編輯:指包括相同的正則表達式的這一擴展版本,這可能會使事情更清楚一點:

my @names = $conditions =~ m{ 
    s \(   # match a literal s and opening parenthesis 
     (   # then capture in a group 
      [^)]* # a sequence a zero or more 
        # non-right-parenthesis characters 
     ) 
    \)    # followed by a literal closing parenthesis 
}gx;    # and return all of the groups that matched 
0
my @jobnames; 
while($conditions =~ m/s\(([^)]*)\)/g) { 
    push @jobnames, $1; 
} 
+0

這很有道理,雖然我不需要@jobname使它成爲一個數組,因爲可能有多個工作名稱? – Brandon 2011-04-13 16:56:53

+0

啊,我不認爲我很清楚輸入是什麼樣子,因爲它沒有在你的問題上劃定界限。修訂。 – geoffspear 2011-04-13 16:58:08

+0

對不起,我應該在這個 – Brandon 2011-04-13 17:00:47

0

你可能需要做兩件事情:

  • 斯普利特在任andor
  • 輸入取出s()

下面是使用split做到這一點的一種方式然後map

@temp = map({/s\(([^)]+)\)/} split(/\s+(?:and|or)\s+/, $conditions)); 

或稍多清楚:

# Break apart on "and" or "or" 
@parts = split(/\s+(?:and|or)\s+/, $conditions); 
# Remove the s() bit 
@temp = map({/s\(([^)]+)\)/} @parts); 
0

假設沒有嵌套的括號。

$_ = 's(job_name1) or s(job_name2) or s(job_name3) and s(job_name4)'; 

my @jobs = /\((.+?)\)/g; 

print "@jobs\n"; 
相關問題