如何使用正则表达式获取已创建表的名称?

时间:2016-05-30 12:17:44

标签: ruby regex

我有一个包含以下内容的文件:

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

对我来说最有趣和令人困惑的部分是使用正则表达式我必须以某种方式获取表的名称。

例如:

animals

如何使用正则表达式执行此操作?

2 个答案:

答案 0 :(得分: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
----------------------------------------------------------------------

答案 1 :(得分: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 «"»