2014-01-06 51 views
1

我試圖找回在這個SQL語句中的字段的值,但是我遇到了麻煩轉義引號字符:檢索引號之間的文本,包括轉義引號

sql = "INSERT INTO `shops` VALUES (35723,'Counsel\'s kitchen');" 

我玩的變種以下,其中沒有一個是令人滿意的:

re.select("\(\d*, '([^']*)',", sql); 

即:

\(\d*, ' Opening parentheses followed by any amount of numerals followed by a comma, followed by a space, followed by a single quote. 
([^']*) Retrieve all characters other than a single quote. 
',  Single quote, comma 

我迄今爲止最好的嘗試:

re.select("\(\d*, '(\.*)','", sql); 

即:

\(\d*, ' Opening parentheses followed by any amount of numerals followed by a comma, followed by a space, followed by a single quote. 
(\.*)  Retrieve all characters. 
','  Single quote, comma, single quote. 

不過,我真的想以此來表達「每個人的性格,包括兩個字符\',但不包括單個字符'。我曾考慮過用一些不太明顯的字符串替換\',然後執行'(\.*)',然後用'(不需要轉義字符,因爲它不再需要)替換不明確的字符串。然而,作爲Python,肯定有一個更聰明的方法!

請注意,字符串實際上是重複的實際產出大量的時間,而且我確實需要的所有值(理想情況下在列表中):

sql = """ 
INSERT INTO `shops` VALUES (35723,'Counsel\'s kitchen','Some address'),(32682,'Anderson and his bar','12 Main street'),(32491,'Sid\'s guitar\'s string','Old London'),(39119,'Roger\'s wall',''),(45914,'David drinks a beer','New London'); 
""" 
+1

比方說,你可以提取值部分你可以使用[this regex](http://regex101.com/r/bY4xU8)'('| \「)(?:\\\ 1 |(!!\ 1)。)* \ 1 | \ d + '。如果你沒有得到答案,我會盡力在以後回覆你。 – HamZa

+0

@HamZa:很高興見到你!我會玩這個正則表達式,並感謝你介紹我到'regex101.com'網站。 – dotancohen

+0

你解決了你的問題嗎? – HamZa

回答

2

Buildung在@HamZa的建議 當你可以保證單引號就會更容易組更大的背景:

'(?:\\'|[^'])*' 

否則,如果添加其他組必須更新反向引用

這也應該稍微快一點,因爲它沒有前景 - 如果你在乎。 (據正則表達式頁:相對於200步114步)

如果同時需要,出於性能的考慮,這也將工作(根據需要逃避"

'(?:\\'|[^'])*'|"(?:\\"|[^"])*" 

所有這些解決方案有一個小瑕疵對於損壞輸入如

'Counsel\'s kitchen', 'tes\\t\' 

最後一組仍將匹配!

All together

1

你能說你使用的是什麼版本的Python?在我的2.7,它似乎做正確的事與逃脫報價內「」」了,所以,你可以提取數據,這樣一個列表的列表:

[re.split("'?,'",t.strip("'")) for t in re.findall("\((.*?)\)",sql)] 
+0

謝謝。我可以讓正則表達式工作,但我不喜歡它是如何表達的(不可維護,不靈活,取決於具體的結局)。我真的很想表達「每個字符,包括兩個字符的字符串'\'',但不包括單個字符'''」。 – dotancohen