2

Python 3.6. I'm trying to create a REGEXP function for sqlite3. I have the error : OperationalError: wrong number of arguments to function REGEXP()

Here is my code :

import sqlite3
import re

def fonctionRegex(mot):
    patternRecherche = re.compile(r"\b"+mot.lower()+"\\b")
    return patternRecherche.search(item) is not None

dbName = 'bdd.db'
connexion = sqlite3.connect(dbName)
leCursor = connexion.cursor()
connexion.create_function("REGEXP", 1, fonctionRegex)

mot = 'trump'
data = leCursor.execute('SELECT * FROM tweet WHERE texte REGEXP ?',mot).fetchall()

Thanks

2 Answers 2

6

You do something wrong. That is more correct example

import sqlite3
import re


def functionRegex(value, pattern):
    c_pattern = re.compile(r"\b" + pattern.lower() + r"\b")
    return c_pattern.search(value) is not None


connection = sqlite3.connect(':memory:')
cur = connection.cursor()
cur.execute('CREATE TABLE tweet(msg TEXT)')
cur.execute('INSERT INTO tweet VALUES("This is a test message")')
cur.execute('INSERT INTO tweet VALUES("Another message")')

connection.create_function("REGEXP", 2, functionRegex)

print(cur.execute('SELECT * FROM tweet WHERE REGEXP(msg, ?)', ('test',)).fetchall())
print(cur.execute('SELECT * FROM tweet WHERE REGEXP(msg, ?)', ('message',)).fetchall())
print(cur.execute('SELECT * FROM tweet WHERE ? REGEXP msg', ('message',)).fetchall())

will print

[('This is a test message',)]
[('This is a test message',), ('Another message',)]
[('This is a test message',), ('Another message',)]
0
2

The documentation says:

The REGEXP operator is a special syntax for the regexp() user function. … the "X REGEXP Y" operator will be implemented as a call to "regexp(Y,X)".

Your function must have two parameters.

2
  • So i have to write data = leCursor.execute('SELECT * FROM tweet WHERE texte pattern REGEXP ?',mot).fetchall() and connexion.create_function("REGEXP", 2, fonctionRegex) ?
    – TmSmth
    Commented Apr 27, 2018 at 16:27
  • The function is fonctionRegex.
    – CL.
    Commented Apr 27, 2018 at 16:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.