Alexander Shmatko Alexander Shmatko - 6 months ago 10
Ruby Question

How to get a name of created table with regular expression?

I have a file with the following content:

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


The most interesting and confusing part to me is that using regexp I have somehow to fetch name of the table.

For example:

animals


How can I do this using regular expressions?

Answer

Description

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

Regular expression visualization

Example

Live Demo

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

Explanation

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
----------------------------------------------------------------------