暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

sqlite的通配符

与C同行 2021-07-14
2290
在正则表达式中.可以匹配任意一个字符,.*可以匹配任意多个字符。这样真的很厉害,在模糊匹配中用处很大,那么在sqlite中有没有类似的表示方法呢?有的,sqlite中有两个通配表达式可以实现模糊匹配,它们就是like指定的表达式和glob指定的表达式。
like指定的表达式中%匹配任意个字符,_匹配任意一个字符,并且对匹配字符的大小写不敏感;glob指定的表达式中*匹配任意个字符,?匹配任意一个字符,但是对匹配字符的大小写敏感。
另外补充一下andor逻辑运算符,源码如下:
""" 匹配通配符

1.like与%和_配合使用,%匹配任意个字符,_匹配单个字符,大小写不敏感
2.glob与*和?配合使用,*匹配任意个字符,?匹配单个字符,大小写敏感
3.and/or,and要求连接的表达式都为真则为真,否则为假,
or要求连接的表达式至少有一个真则为真,否则为假

the statistics of this file:
lines(count) understand_level(h/m/l) classes(count) functions(count) fields(count)
000000000072 ----------------------l 00000000000000 0000000000000001 ~~~~~~~~~~~~~
"""


import time
import sqlite3

__author__ = '与C同行'


def print_pretty_outcome(cursor):
print('-' * 80)
all_outcome = cursor.fetchall()
for column_desc in cursor.description:
print(f'{column_desc[0]:<20}', end='')
print()
for item in all_outcome:
for cell in item:
try:
print(f'{cell:<20}', end='')
except TypeError:
cell = 'None'
print(f'{cell:<20}', end='')
print()
print('-' * 80)
print()


if __name__ == '__main__':
print(f'当前时间:{time.ctime()}')
conn = sqlite3.connect('learn.db')
c = conn.cursor()

print('like与%和_配合使用')
print('like对文本字符大小写不敏感')
print('%匹配任意字符')
c.execute('select * from report_tb where description like "a%"')
print_pretty_outcome(c)

print('_匹配单个字符')
c.execute('select * from report_tb where description like "B_y"')
print_pretty_outcome(c)

print('glob与*和?配合使用')
print('glob对文本字符大小写敏感')
print('*匹配任意字符')
c.execute('select * from report_tb where description glob "a*"')
print_pretty_outcome(c)

print('?匹配单个字符')
c.execute('select * from report_tb where description glob "b?Y"')
print_pretty_outcome(c)

print('and/or连接表达式')
print('and的与逻辑')
c.execute('select * from report_tb where description glob "a*" and achievement > 10')
print_pretty_outcome(c)

print('or的或逻辑')
c.execute('select * from report_tb where description glob "b?Y" or achievement = 77')
print_pretty_outcome(c)

c.close()
conn.close()

结果如下:

总结:只有一句话,注意glob表达式对大小写敏感。




文章转载自与C同行,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论