2016-06-10 16 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

相关问题