2016-05-30 64 views
0

我有以下內容的文件:如何使用正則表達式獲取已創建表的名稱?

create_table "animals", force: :cascade do |t| 
    t.integer "name" 
    t.datetime "created_at", null: false 
end 

最有趣和令人困惑的部分,我是使用正則表達式我必須以某種方式獲取表的名稱。

例如:

animals 

我怎樣才能做到這一點使用正則表達式?

+3

閱讀有關[*捕獲組*](http://www.regular-expressions.info/brackets.html)。 –

+0

你的問題的答案是「是的」,但大概這不是你正在尋找的答案。那麼你真正的問題是什麼?你有哪些麻煩? –

+0

'/ create_table「(\ S *)」/ g' [在此測試](https://regex101.com/r/xZ6rI5/2) – jlib

回答

1

說明
^create_table\s*"([^"]+)" 

Regular expression visualization

現場演示

https://regex101.com/r/kI7yZ1/1

說明

NODE      EXPLANATION 
---------------------------------------------------------------------- 
^      the beginning of a "line" 
---------------------------------------------------------------------- 
    .{12}     any character except \n (12 times) 
---------------------------------------------------------------------- 
    (?:      group, but do not capture: 
---------------------------------------------------------------------- 
    001      '001' 
---------------------------------------------------------------------- 
    |      OR 
---------------------------------------------------------------------- 
    005      '005' 
---------------------------------------------------------------------- 
)      end of grouping 
---------------------------------------------------------------------- 
+0

很好的解釋! –

+0

不錯!但我可能會失去開始的主播。它可能不是第一個。也許允許單引號字符串。即'create_table \ s *([「'])((?:(?!\ 1)。)+)\ 1'。它會移動表的名字來捕獲組2。 – ClasG

1
result = subject.scan(/create_table "(.*?)"/i) 

create_table "(.*?)" 
Options: Case insensitive; Exact spacing; Dot doesn’t match line breaks 
Match the character string 「create_table "」 literally (case insensitive) «create_table "» 
Match the regex below and capture its match into backreference number 1 «(.*?)» 
    Match any single character that is NOT a line break character (line feed) «.*?» 
     Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?» 
Match the character 「"」 literally «"»