我有一個如下所示的字串:
sql = """DROP TABLE IF EXISTS table1;
ALTER TABLE table1 DROP PRIMARY KEY;
INSERT INTO table1 (id, created, name, telefonnummer, erPatient_id) VALUES
(1, '2015-08-06 12;09:08', ' ', ' ', 16528),
(2, '2015-08-06 12:43:11', ' ', ' ', 16529)
;
INSERT INTO table2 (comment, id) VALUES
('hello this is a semicolon ;', 2);"""
我想得到陳述句 INSERT INTO table1:
INSERT INTO table1 (id, created, name, telefonnummer, erPatient_id) VALUES
(1, '2015-08-06 12;09:08', ' ', ' ', 16528),
(2, '2015-08-06 12:43:11', ' ', ' ', 16529)
;
我無法拆分字串,sql.split(';)因為要插入的 VALUES 中有分號。
我嘗試過使用正則運算式但沒有成功:
import re
pattern_string = r"INSERT INTO bezugsperson[(]*[^)] \)[^)]"
q = re.findall(pattern_string, data, re.MULTILINE | re.DOTALL)
在真正的字串中,將有數千個值要插入和數十個表。
uj5u.com熱心網友回復:
用
import re
pattern_string = r"\bINSERT INTO \w \s.*?;\s*$"
q = re.findall(pattern_string, data, re.MULTILINE | re.DOTALL)
請參閱正則運算式證明。
解釋
NODE EXPLANATION
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
INSERT INTO 'INSERT INTO '
--------------------------------------------------------------------------------
\w word characters 1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
.*? any character (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
; ';'
--------------------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ end of a line
uj5u.com熱心網友回復:
正則運算式來捕獲INSERT INTO table1和之間的所有內容\n;:
pattern_string = "INSERT INTO table1 .*\n;"
q = re.findall(pattern_string, sql, re.DOTALL)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358141.html
