How do I use regex in a SQLite query?

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

    As others pointed out already, REGEXP calls a user defined function which must first be defined and loaded into the the database. Maybe some sqlite distributions or GUI tools include it by default, but my Ubuntu install did not. The solution was

    sudo apt-get install sqlite3-pcre
    

    which implements Perl regular expressions in a loadable module in /usr/lib/sqlite3/pcre.so

    To be able to use it, you have to load it each time you open the database:

    .load /usr/lib/sqlite3/pcre.so
    

    Or you could put that line into your ~/.sqliterc.

    Now you can query like this:

    SELECT fld FROM tbl WHERE fld REGEXP '\b3\b';
    

    If you want to query directly from the command-line, you can use the -cmd switch to load the library before your SQL:

    sqlite3 "$filename" -cmd ".load /usr/lib/sqlite3/pcre.so" "SELECT fld FROM tbl WHERE fld REGEXP '\b3\b';"
    

    If you are on Windows, I guess a similar .dll file should be available somewhere.

提交回复
热议问题