正则表达式 python 和 sqlite 的问题

发布于 2024-10-24 09:41:21 字数 563 浏览 0 评论 0原文

我尝试在 sqlite 数据库上使用带有 python 的正则表达式来检查具有模式的字符串。 当我尝试使用“使用”模式搜索具有“的字符串”时,我遇到问题 例如:

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())

我应该在正则表达式之前 \" ,其他方式编译器不喜欢...语法错误

[(1, 'aaa"test"')]
[] <????? should found 

有人知道该怎么做吗?

我的正则表达式函数:con.create_function("regexp", 2, regexp)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

像你 2024-10-31 09:41:21

使用参数化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)

yield

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

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"',)]
舂唻埖巳落 2024-10-31 09:41:21

您可以使用三重转义符或原始字符串。

您的做法:

>>> print("select subject from articles where  subject regexp '\"test\"' ")
select subject from articles where  subject regexp '"test"'

使用原始字符串,即 r'string with ar in front':

>>> print(r"select subject from articles where  subject regexp '\"test\"' ")
select subject from articles where  subject regexp '\"test\"' 

或三重转义符 (\\\):

>>> print("select subject from articles where  subject regexp '\\\"test\\\"' ")
select subject from articles where  subject regexp '\"test\"'

You can use triple escapes, or a raw string.

Your doing:

>>> print("select subject from articles where  subject regexp '\"test\"' ")
select subject from articles where  subject regexp '"test"'

Use a raw string, which is a r'string with a r in front':

>>> print(r"select subject from articles where  subject regexp '\"test\"' ")
select subject from articles where  subject regexp '\"test\"' 

Or triple escapes (\\\):

>>> print("select subject from articles where  subject regexp '\\\"test\\\"' ")
select subject from articles where  subject regexp '\"test\"'
一腔孤↑勇 2024-10-31 09:41:21

另一个参数化查询示例...

对于必须向数据库提供自己的 REGEX 函数的情况 - 我想 Python sqlite3 并不总是默认设置它。

在另一个示例中,自定义 REGEX 函数为每个匹配项编译相同的表达式。有办法解决这个问题。下面的示例还在定义 REGEX 操作的另一种方法的底部有一个注释。

通过为每个查询创建自定义函数并仅编译表达式一次,您可以在每次使用表达式(针对每个匹配)处理大量数据的查询时编译表达式。 self._conn 下面是数据库连接,curs 是其中的游标。

    # Form an expression to match nicknames with the last 3 characters
    # varying.
    nick_expr = re.sub(r"[0-9_\-|]{0,3}$", r"[0-9_\-|]{0,3}$", nick)
    nick_expr = re.compile(nick_expr, re.I)

    # Create custom sqlite3 function using the compiled expression.
    self._conn.create_function("NICKEXPR",
                               1,
                               lambda nick: nick_expr.match(nick) != None)

    # Create temporary table from first pass query.
    curs.execute(
        """ CREATE TEMP TABLE temp_table1 AS
           SELECT  DISTINCT *
           FROM    users
           WHERE   NICKEXPR(nick)
               OR  host LIKE ?
               OR  (account<>'' AND account LIKE ?)
               OR  (address<>'' AND address=?)
       """, (host, account, address))

    # Set up the REGEXP operator/function for the sqlite3 database.
    #self._conn.create_function(
    #                       'REGEXP', 2, 
    #                       lambda exp, item : re.find(exp, item) != None)

Another parameterized query example...

For the situation where you have to supply your own REGEX function to the database - I guess Python sqlite3 doesn't always have it set up by default.

In another example, the custom REGEX function is compiling the same expression for each and every match. There's a way around that. The example below also has a comment at the bottom of another way to define the REGEX operation.

You can get around compiling the expression every time the expression is used (for each match) for queries dealing with a lot of data by creating a custom function for each query and compiling the expression only once. Below self._conn is the database connection, and curs is a cursor from it.

    # Form an expression to match nicknames with the last 3 characters
    # varying.
    nick_expr = re.sub(r"[0-9_\-|]{0,3}$", r"[0-9_\-|]{0,3}$", nick)
    nick_expr = re.compile(nick_expr, re.I)

    # Create custom sqlite3 function using the compiled expression.
    self._conn.create_function("NICKEXPR",
                               1,
                               lambda nick: nick_expr.match(nick) != None)

    # Create temporary table from first pass query.
    curs.execute(
        """ CREATE TEMP TABLE temp_table1 AS
           SELECT  DISTINCT *
           FROM    users
           WHERE   NICKEXPR(nick)
               OR  host LIKE ?
               OR  (account<>'' AND account LIKE ?)
               OR  (address<>'' AND address=?)
       """, (host, account, address))

    # Set up the REGEXP operator/function for the sqlite3 database.
    #self._conn.create_function(
    #                       'REGEXP', 2, 
    #                       lambda exp, item : re.find(exp, item) != None)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文