gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:29:50 26 4
gpt4 key购买 nike

我正在尝试检索此 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');
"""

最佳答案

基于@HamZa 的建议当您可以保证单引号时,在更大的上下文中进行分组会变得更容易:

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

否则,如果您添加其他组,则必须更新反向引用

这也应该稍微快一些,因为它没有前瞻 - 如果你关心的话。 (根据正则表达式页面:114 个步骤而不是 200 个步骤)

如果您两者都需要,出于性能原因,这也可以(根据需要转义 ")

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

所有这些解决方案在损坏输入方面都有一个小缺陷,例如

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

最后一组仍然会被匹配!

All together

关于python - 检索引号之间的文本,包括转义引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20946602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com