2016-11-30 52 views
2

我希望能夠像下面那樣取出一個字符串,並提取第一個參數(id),然後用它打印出來。我一直在考慮拆分python,但通常我必須拆分2或3次才能獲得可用的東西。解析python中的sql查詢

這裏是我試圖解析字符串的例子:

EntryError(u"(sqlite3.IntegrityError) UNIQUE constraint failed: 
role.name, role.domain_id [SQL: u'INSERT INTO table1 (id, name, 
domain_id, extra) VALUES (?, ?, ?, ?)'] [parameters: ('id', 
'fake1name', '<<null>>', '{}')]",) 

我有嘗試的東西,如:

e = e.split("\'") 
e = e.split(",") 

但是,這給了我,必須進一步解析怪異的字符串。有沒有更簡單的方法總是從"[parameters: ('id', 'fake1name', '<<null>>', '{}')]"id

這裏是我的代碼:

except exception.EntryError as e: 

    query = str(e) 
    # example of me using split to try and reduce the string 
    parsedstr = query.split("[") 
    parsedstr = parsedstr.split("\'") 

    # This will give me id like I want but it doesn't seem efficient 
    # prints: id 
    print parsedstr[1] 
+2

您能否顯示剩餘的代碼 - 您是否確實有權訪問遊標或異常實例本身?謝謝。 – alecxe

+0

@alecxe added :) – ayonpyth

+0

你想分析什麼字符串?你真的試圖解析上面的EntryError對象中的消息嗎? –

回答

1

您可以使用正則表達式。

import re 

... 

except exception.EntryError as e: 
    print re.search("\[parameters: \('([^']+)", str(e)).group(1) 

這將搜索例外字符串的[parameters: ('第一次出現,並開始從該點匹配,直到遇到一個'