2012-07-20 33 views
0

我想從SQL查詢中提取表名。Ruby正則表達式 - 提取字

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

我想格蘭結果["tbl1", "tbl2"]

這是沒有必要的,將有多個表查詢。在這種情況下,查詢將

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

和預期結果["tbl1"]

提前感謝!

回答

2

請注意,這可能會匹配SQL字符串中的內容,因此並不完美。

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"] 
+0

非常感謝! – Sayuj 2012-07-24 06:43:56