2011-04-16 81 views
1
def match_line regex 
    @line.match(regex) if !regex.is_a?(Array) 
    regex.each {|rgx| 
     results = @line.match(rgx) 
     return results if !results.nil? 
    } 
    return nil 
end 

這看起來像的東西,可能在一個行慣用的方式來完成的數組找到一個正則表達式匹配,而我只是沒有看到如何。從正則表達式

+1

你的問題不清楚。你想看看數組中的某個正則表達式匹配了什麼嗎?或者,你想找出哪些正則表達式匹配? – 2011-04-16 19:23:46

+0

我打算在第二行之前加上'return',我想。 – sawa 2011-04-16 19:46:03

回答

5
[*regex].map{ |re| @line.match re }.compact.first 

Array(regex).map{ |re| @line.match re }.compact.first 
+0

謝謝,那是如果Array不是一個變量,那麼Array()是否會將一個變量轉換爲一個數組?另外,我假設所有的正則表達式都匹配,並且在第一次匹配後沒有跳出的方法嗎? – 2011-04-16 19:34:44

+0

nm on Array ()..這是一個非常有用的函數 – 2011-04-16 19:41:38

+0

這是正確的,它將遍歷所有正則表達式中的正則表達式,但假設這種情況相對較少,這不會造成什麼大問題。懷疑績效增益會值得失去可讀性。 – 2011-04-16 23:31:08

1
[*regex].find{|r| @line.match(r)} 
return $~ #will return the last MatchedData returned, otherwise nil. 

$~將返回最後一次返回的MatchedData,否則返回nil。

+1

:(完整神奇的全局變量是不可讀的,正如您的解釋性註釋所示。 – 2011-04-16 19:11:47

+0

與該行關聯的註釋看起來對我來說沒有問題,尤其是因爲它實際上是一行有問題 – 2011-04-16 19:16:25

0
def match_line regex 
    [*regex].each { |r| return r if (r = @line.match r) } 
end 
0

這是一個優選的,慣例來傳遞參數在這種情況下像

match_line(regex1, regex2, ...) 

match_line(*array_of_regexes) 

而不是

match_line([regex1, regex2, ...]) 

match_lines(array_of_regexes) 

這樣您就陣列的煩躁調節是不必要的。

def match_line *regex 
    regex.detect{|r| @line =~ r} 
    Regexp.last_match 
end