2016-06-10 17 views
0

我很難用組捕獲。我有以下文字:如何使用組捕獲來選擇行尾的單詞?

class Rename < ActiveRecord::Migration 
    def change 
    rename_table :users, :vendors 
    rename_table :places, :venues 
    end 
end 

在這種情況下,我需要提取廠商場館

我試圖使用類似/rename_table.*([]+)$/,但無濟於事。

我該如何做到這一點?

回答

1
▶ text.scan(/rename_table.+:(\w+)\s*$/).flatten 
#⇒ [ 
# [0] "vendors", 
# [1] "venues" 
# ] 
2

像這樣的事情可能會爲你工作:

/rename_table.+:(\S+)/g 

它將存儲的最後一個字包含rename_table在比賽組$1vendorsvenues:表格線前綴。

Try it online

1

你不需要正則表達式:

str = %q{ 
class Rename < ActiveRecord::Migration 
    def change 
    rename_table :users, :vendors 
    rename_table :places, :venues 
    end 
end 
} 

str.each_line do |line| 
    puts line.split[-1] if line.lstrip.start_with? 'rename_table' 
end 

--output:-- 
:vendors 
:venues 

在任何情況下,該組中你的正則表達式是([]+)。括號是特殊的正則表達式字符,它們表示一個字符類別,您可以在其中指定要匹配的字符,例如, [xyz]。該字符類將匹配一個字符,即xyz。在你的情況下,字符類是空的,這在紅寶石2.2產生一個錯誤:

空字符類:/rename_table.*([]+)$/

從本質上講,紅寶石他說,Wtf??! You specified a character class with no characters. Are you really trying to say, I want to match one character that is in the character class consisting of no characters?. I don't think so! Error! Error! Error!

+0

我認爲OP希望'vendors'和'未使用'前綴venues':'' – andlrc

+0

提出line.split [-1] [1 ..- 1]' – 7stud

相關問題