pr0*_*r0m 10 python regex sqlite
我尝试在sqlite数据库上使用带有python的正则表达式检查带有模式的字符串.当我尝试使用"使用patern使用"搜索字符串时,我有问题例如:
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())
Run Code Online (Sandbox Code Playgroud)
我应该"在regexp之前其他方式编译器不喜欢...语法错误
[(1, 'aaa"test"')]
[] <????? should found
Run Code Online (Sandbox Code Playgroud)
有人知道怎么做吗?
我的正则表达式函数:con.create_function("regexp",2,regexp)
unu*_*tbu 25
使用参数化的sql.然后你不需要自己逃避引号:
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)
Run Code Online (Sandbox Code Playgroud)
产量
[(u'aaa"test"',)]
Run Code Online (Sandbox Code Playgroud)