如何使用正则表达式匹配数据库中的数据?

时间:2018-11-16 18:40:20

标签: mysql regex sqlite

我将正则表达式存储在MySQL(或SQLite3)数据库列中,例如:

Database column screenshot

qus | ans
----- |  -----
(hii?|hell?o) | Hello There...

现在,如果输入匹配hi或hii或helo或hello,则回答返回Hello Hello

if(input == "hi" /*or hii*/){
  return ans; //ans = Hello There
}

有可能吗?如果是,我该怎么办?

2 个答案:

答案 0 :(得分:2)

正则表达式可以来自表列而不是文字:

CREATE TABLE regexps (
    re VARCHAR(99)
);
INSERT INTO regexps (re)
    VALUES ('hii?|hell?o'), ('aloha'), ('bonjour');

SELECT CONCAT('matches ', re)
    FROM regexps
    WHERE "hi, y'all" REGEXP re;
SELECT CONCAT('matches ', re)
    FROM regexps
    WHERE "bonjour and aloha" REGEXP re;
SELECT CONCAT('matches ', re)
    FROM regexps
    WHERE "oops: high" REGEXP re;

...

mysql> SELECT * FROM regexps;
+-------------+
| re          |
+-------------+
| hii?|hell?o |
| aloha       |
| bonjour     |
+-------------+
3 rows in set (0.00 sec)

mysql>     SELECT CONCAT('matches ', re)
    ->         FROM regexps
    ->         WHERE "hi, y'all" REGEXP re;
+------------------------+
| CONCAT('matches ', re) |
+------------------------+
| matches hii?|hell?o    |
+------------------------+
1 row in set (0.01 sec)

mysql>     SELECT CONCAT('matches ', re)
    ->         FROM regexps
    ->         WHERE "bonjour and aloha" REGEXP re;
+------------------------+
| CONCAT('matches ', re) |
+------------------------+
| matches aloha          |
| matches bonjour        |
+------------------------+
2 rows in set (0.00 sec)

mysql>     SELECT CONCAT('matches ', re)
    ->         FROM regexps
    ->         WHERE "oops: high" REGEXP re;
+------------------------+
| CONCAT('matches ', re) |
+------------------------+
| matches hii?|hell?o    |
+------------------------+
1 row in set (0.00 sec)
  

我只想匹配hi或hii或helo或hello,然后回答“ Hello There”

rehii?|hell?oanswerHello There。查询是

SELECT answer FROM regexps WHERE $input REGEXP re LIMIT 1

我添加LIMIT是因为您可能遇到两种不同的正则表达式匹配的情况。

答案 1 :(得分:0)

您可以使用preg matchpreg replace来测试您的正则表达式

示例:

$input = 'hii user';
$output = 'Hi there';
// If your regex matches
if(preg_match('/(hii?|hell?o)/', $input))
{
    // succes;
    // Replace the input by your answer
    echo preg_replace('/(hii?|hell?o)/', $output, $input); // returns Hi there user
}
else
{
    echo 'fail';
}