How do I use regex in a SQLite query?

后端 未结 17 1523
暖寄归人
暖寄归人 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:40

    my solution in python with sqlite3:

       import sqlite3
       import re
    
       def match(expr, item):
            return re.match(expr, item) is not None
    
       conn = sqlite3.connect(':memory:')
       conn.create_function("MATCHES", 2, match)
       cursor = conn.cursor()
       cursor.execute("SELECT MATCHES('^b', 'busy');")
       print cursor.fetchone()[0]
    
       cursor.close()
       conn.close()
    

    if regex matches, the output would be 1, otherwise 0.

    0 讨论(0)
  • 2020-11-22 06:40

    You may consider also

    WHERE x REGEXP '(^|\D{1})3(\D{1}|$)'
    

    This will allow find number 3 in any string at any position

    0 讨论(0)
  • 2020-11-22 06:41

    In case if someone looking non-regex condition for Android Sqlite, like this string [1,2,3,4,5] then don't forget to add bracket([]) same for other special characters like parenthesis({}) in @phyatt condition

    WHERE ( x == '[3]' OR
            x LIKE '%,3]' OR
            x LIKE '[3,%' OR
            x LIKE '%,3,%');
    
    0 讨论(0)
  • 2020-11-22 06:42

    An exhaustive or'ed where clause can do it without string concatenation:

    WHERE ( x == '3' OR
            x LIKE '%,3' OR
            x LIKE '3,%' OR
            x LIKE '%,3,%');
    

    Includes the four cases exact match, end of list, beginning of list, and mid list.

    This is more verbose, doesn't require the regex extension.

    0 讨论(0)
  • 2020-11-22 06:42

    In Julia, the model to follow can be illustrated as follows:

    using SQLite
    using DataFrames
    
    db = SQLite.DB("<name>.db")
    
    register(db, SQLite.regexp, nargs=2, name="regexp")
    
    SQLite.Query(db, "SELECT * FROM test WHERE name REGEXP '^h';") |> DataFrame
    
    0 讨论(0)
提交回复
热议问题