2011-02-13 30 views
6

請原諒我的無知,我是Ruby的新手。Ruby:在多個目錄中的多個文件中搜索正則表達式

我知道如何搜索字符串,或用正則表達式甚至一個單一的文件:

str = File.read('example.txt') 
match = str.scan(/[0-9A-Za-z]{8,8}/) 

puts match[1] 

我知道如何在多個文件和目錄

pattern = "hello" 

Dir.glob('/home/bob/**/*').each do |file| 
    next unless File.file?(file) 
     File.open(file) do |f| 
      f.each_line do |line| 
       puts "#{pattern}" if line.include?(pattern) 
     end 
    end 
end 

搜索靜態短語我無法弄清楚如何針對多個文件和目錄使用我的正則表達式。任何和所有的幫助,非常感謝。

回答

5

那麼,你是非常接近。首先製作模式的RegExp對象:

pattern = /hello/ 

或者,如果你試圖讓一個正則表達式從字符串(如通過在命令行上),你可以嘗試:

pattern = Regexp.new("hello") 
# or use first argument for regexp 
pattern = Regexp.new(ARGV[0]) 

現在你的時候正在搜索,line是一個字符串。您可以使用matchscan獲得與您的模式相匹配的結果。

f.each_line do |line| 
    if line.match(pattern) 
    puts $0 
    end 
    # or 
    if !(match_data = line.match(pattern)).nil? 
    puts match_data[0] 
    end 
    # or to see multiple matches 
    unless (matches = line.scan(pattern)).empty? 
    p matches 
    end 
end 
+0

非常感謝您的回覆。我遇到顯示正則表達式搜索結果的問題。我假設「puts」命令將顯示與正則表達式匹配的數據是否正確? – roobnoob 2011-02-13 06:18:27