regexp python 和 sqlite 的问题

2023-10-10数据库问题
1

本文介绍了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 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

如何在MySQL中为每个组选择第一行?
How to select the first row for each group in MySQL?(如何在MySQL中为每个组选择第一行?)...
2024-04-16 数据库问题
13

MySQL - 获取最低值
MySQL - Fetching lowest value(MySQL - 获取最低值)...
2024-04-16 数据库问题
8

在 cmakelist.txt 中添加和链接 mysql 库
Add and link mysql libraries in a cmakelist.txt(在 cmakelist.txt 中添加和链接 mysql 库)...
2024-04-16 数据库问题
41

考勤数据库的良好数据库设计(架构)是什么?
What is a good database design (schema) for a attendance database?(考勤数据库的良好数据库设计(架构)是什么?)...
2024-04-16 数据库问题
7

子类型的表关系
Table relationship for subtypes(子类型的表关系)...
2024-04-16 数据库问题
10