Problem with regexp python and sqlite(regexp python 和 sqlite 的问题)
问题描述
我尝试在 sqlite 数据库上使用带有 python 的正则表达式检查具有模式的字符串.当我尝试搜索字符串时,我遇到了问题,其中包含 " 和使用 " 的模式例如:
I try to check a string with a pattern using a regex with python on a sqlite database. I have problem when I try de search string having " with a patern using " For exemple:
cur.execute("insert into articles(id,subject) values (1,'aaa"test"')")
cur.execute("select id,subject from articles where id = 1")
print (cur.fetchall())
cur.execute("select subject from articles where subject regexp '"test"' ")
print (cur.fetchall())
我应该 " 在正则表达式之前编译器不喜欢...语法错误
I should " before regexp other way compiler dont like... syntaxe error
[(1, 'aaa"test"')]
[] <????? should found
有人知道怎么做吗?
我的正则表达式函数:con.create_function("regexp", 2, regexp)
My regexp function :con.create_function("regexp", 2, regexp)
推荐答案
使用参数化的 sql.然后你不需要自己转义引号:
Use parametrized sql. Then you don't need to escape the quotes yourself:
import sqlite3
import re
def regexp(expr, item):
reg = re.compile(expr)
return reg.search(item) is not None
conn = sqlite3.connect(':memory:')
conn.create_function("REGEXP", 2, regexp)
cursor = conn.cursor()
cursor.execute('CREATE TABLE foo (bar TEXT)')
cursor.executemany('INSERT INTO foo (bar) VALUES (?)',[('aaa"test"',),('blah',)])
cursor.execute('SELECT bar FROM foo WHERE bar REGEXP ?',['"test"'])
data=cursor.fetchall()
print(data)
收益
[(u'aaa"test"',)]
这篇关于regexp python 和 sqlite 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:regexp python 和 sqlite 的问题


- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- SQL 临时表问题 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01