Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

regex - Problem with regexp python and sqlite

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 

Somebody know how to do that ?

My regexp function :con.create_function("regexp", 2, regexp)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

yields

[(u'aaa"test"',)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...