7.4.14 带正则表达式的查询
SQLite支持很多与SQL语句关联的特殊用户函数。例如,可以用以下语法在查询中使用函数regexp检查一个列的字符串值是否与一个正则表达式匹配。
SELECT * FROM table
WHERE column REGEXP ‘.pattern.’
下面的例子将一个函数与regexp()关联,以使用Python的re模块来完成值的测试。
import re
import sqlite3
db_filename = 'todo.db'
def regexp(pattern,input):
return bool(re.match(pattern,input))
with sqlite3.connect(db_filename) as conn:
conn.row_factory = sqlite3.Row
conn.create_function('regexp',2,regexp)
cursor = conn.cursor()
pattern = '.*[wW]rite [aA]bout.*'
cursor.execute(
"""
select id,priority,details,status,deadline from task
where details regexp :pattern
order by deadline,priority
""",
{'pattern':pattern},
)
for row in cursor.fetchall():
task_id,priority,details,status,deadline = row
print('{:2d} [{:d}] {:<25} [{:<8}] ({})'.format(
task_id,priority,details,status,deadline))
输出是details列与模式匹配的所有任务。
运行结果: