How do I use regex in a SQLite query?

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

    A SQLite UDF in PHP/PDO for the REGEXP keyword that mimics the behavior in MySQL:

    $pdo->sqliteCreateFunction('regexp',
        function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS')
        {
            if (isset($pattern, $data) === true)
            {
                return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
            }
    
            return null;
        }
    );
    

    The u modifier is not implemented in MySQL, but I find it useful to have it by default. Examples:

    SELECT * FROM "table" WHERE "name" REGEXP 'sql(ite)*';
    SELECT * FROM "table" WHERE regexp('sql(ite)*', "name", '#', 's');
    

    If either $data or $pattern is NULL, the result is NULL - just like in MySQL.

提交回复
热议问题