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

flvlnr44  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(397)

我将正则表达式存储在mysql(或sqlite3)数据库列中,如下所示:

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

现在如果输入匹配hi或hii或helo或hello,那么回答return hello

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

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

nfzehxib

nfzehxib1#

regexp可以来自表列,而不是文本:

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?o , answerHello There . 查询是

SELECT answer FROM regexps WHERE $input REGEXP re LIMIT 1

我加上 LIMIT 因为您可能遇到两个不同regexp匹配的情况。

z0qdvdin

z0qdvdin2#

您可以使用preg match和preg 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';
}

相关问题