How do I use regex in a SQLite query?

后端 未结 17 1747
暖寄归人
暖寄归人 2020-11-22 05:57

I\'d like to use a regular expression in sqlite, but I don\'t know how.

My table has got a column with strings like this: \"3,12,13,14,19,28,32\" Now if I type \"whe

17条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 06:36

    With python, assuming con is the connection to SQLite, you can define the required UDF by writing:

    con.create_function('regexp', 2, lambda x, y: 1 if re.search(x,y) else 0)
    

    Here is a more complete example:

    import re
    import sqlite3
    
    with sqlite3.connect(":memory:") as con:
        con.create_function('regexp', 2, lambda x, y: 1 if re.search(x,y) else 0)
        cursor = con.cursor()
        # ...
        cursor.execute("SELECT * from person WHERE surname REGEXP '^A' ")
    
    
    

提交回复
热议问题