Python 检索引号之间的文本,包括转义引号

Python 检索引号之间的文本,包括转义引号,python,regex,string,Python,Regex,String,我正在尝试检索此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

我正在尝试检索此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
\(\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.
我迄今为止最好的尝试是:

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
\(\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,肯定有更聪明的方法

请注意,字符串实际上在实际输出中重复了很多次,我确实需要所有值(理想情况下是在列表中):


基于@HamZa的建议 当您能够保证单引号时,就更容易在更大的上下文中分组:

'(?:\\'.[^'])*'
否则,如果添加其他组,则必须更新反向引用

这也应该稍微快一点,因为它没有前瞻性-如果你在意的话。(根据regex第页:114步与200步相对)

如果两者都需要,出于性能原因,这也会起作用(根据需要转义

“(?:\\'.[^'])*”|“(?:\\”|[^'])*”
所有这些解决方案在损坏的输入上都有一个小缺陷,比如

“律师厨房”、“tes\\t”
最后一组仍将匹配


您能说出您使用的是哪一版本的Python吗?在我的2.7版中,似乎已经在“”中使用了转义引号,这样您就可以将数据提取为如下列表:

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

假设您可以提取值部分。您可以使用
('\\”(:\\\1(?!\1)。)*\1 |\d+
。如果你没有得到答案,我会稍后再打给你。@HamZa:很高兴看到你这样!我会玩一下这个正则表达式,感谢你介绍我到
regex101.com
网站。你解决了你的问题吗?@HamZa:没有,我正在避免:)我会很快回来并选择答案。谢谢。谢谢,HamZa。我是我无法按照我的意愿表达正则表达式(每个字符,包括两个字符串
\'
,但不包括单个字符
'
),但我可以解析输入并获得所需的输出。我正在选择答案。谢谢。我可以让正则表达式工作,但我不喜欢它的措辞(不可维护,不灵活,取决于特定的结尾)。我真的想用一种方式来表达“每个字符,包括两个字符的字符串
\”
,但不包括单个字符
”。