2013-08-22 73 views
0

我想認識的模式是其名稱不_CODE後綴結尾的表(表名不應該是這樣test_code):如何使用正則表達式來識別該SQL創建表模式

CREATE TABLE test1 
(
    aa INT, -- comment1 
    bb CHAR(10), -- comment2 
    cc INT, -- comment3 
    PRIMARY KEY (aa) 
); 

,這也可能是一個線風格是這樣的:

CREATE TABLE test2(aa INT, bb CHAR(10), cc INT, PRIMARY KEY (aa)); 

我用下面的正則表達式,但沒有奏效:

CREATE TABLE .*\n?\([.\n\;]* 

我想識別他們和在「)」和「;」之間插入句子要這樣:

CREATE TABLE test1 
(
    aa INT, -- comment1 
    bb CHAR(10), -- comment2 
    cc INT, -- comment3 
    PRIMARY KEY (aa) 
)[sentence goes to here]; 

請告訴我該如何解決這個問題。

+0

那麼,你想匹配或替換? – hwnd

+0

匹配create table語句並在「)」和「;」之間插入句子 –

+0

你在用什麼語言? – hwnd

回答

0

可以

import re 
rgx = re.compile(r"^\s*CREATE\s+TABLE\s+([\w\d]+)\s*(\(.*\))\s*;\s*",re.MULTILINE|re.DOTALL) 

def sqlsub(sql, statement): 
    m = rgx.match(sql) 
    if m and not m.group(1).endswith("_code"): 
    return "CREATE TABLE %s %s %s;"%(m.group(1),m.group(2),statement) 
    return None 
+0

實際上這個代碼還有一個問題。因爲我一行一行地讀取SQL代碼,其中包含許多句子,如create table,drop table,alter table ...因此,要將您創建的表句分開以便在sqlsub函數上使用並不容易。 –

+0

爲什麼不直到「;」並追加 – FUD