How do I use regex in a SQLite query?

后端 未结 17 1522
暖寄归人
暖寄归人 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.

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

    If you are using php you can add any function to your sql statement by using: SQLite3::createFunction. In PDO you can use PDO::sqliteCreateFunction and implement the preg_match function within your statement:

    See how its done by Havalite (RegExp in SqLite using Php)

    0 讨论(0)
  • 2020-11-22 06:33
    UPDATE TableName
     SET YourField = ''
    WHERE YourField REGEXP 'YOUR REGEX'
    

    And :

    SELECT * from TableName
     WHERE YourField REGEXP 'YOUR REGEX'
    
    0 讨论(0)
  • 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' ")
    
    
    
    0 讨论(0)
  • 2020-11-22 06:39

    SQLite3 supports the REGEXP operator:

    WHERE x REGEXP <regex>
    

    http://www.sqlite.org/lang_expr.html#regexp

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

    for rails

                db = ActiveRecord::Base.connection.raw_connection
                db.create_function('regexp', 2) do |func, pattern, expression|
                  func.result = expression.to_s.match(Regexp.new(pattern.to_s, Regexp::IGNORECASE)) ? 1 : 0
                end
    
    0 讨论(0)
提交回复
热议问题