简体   繁体   中英

Ruby regex - extract words

I want to extract table names from an SQL query.

SELECT col1, col2, count(1) as count_all,     FROM     tbl1, tbl2 where condition order by column

I want teh result ["tbl1", "tbl2"]

It is not necessary that there will be multiple tables to query. In that case the query will be

SELECT col1, col2, count(1) as count_all,     FROM     tbl1  where condition order by column

And expected result ["tbl1"]

Thanks in advance!

Note that this can potentially match stuff inside a SQL string and therefore is not perfect.

test = [
"SELECT col1, col2, count(1) as count_all FROM tbl1, tbl2 where condition order by column",
"SELECT col1, col2, count(1) as count_all FROM tbl1 where condition order by column",
"SELECT col1, col2, count(1) as count_all FROM tbl1",
]
tests.map { |str| str.match(/\s*from\s*([a-z_0-9]+(?:,\s*[a-z_0-9]+)*)\b/i); $1 }
#=> ["tbl1, tbl2", "tbl1", "tbl1"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM