Problem with regexp python and sqlite

前端 未结 3 1192
余生分开走
余生分开走 2020-12-05 08:48

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 exempl

3条回答
  •  佛祖请我去吃肉
    2020-12-05 09:23

    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"',)]
    

提交回复
热议问题