gpt4 book ai didi

mysql - REGEXP 匹配数字在 MySQL 中始终计算为 true

转载 作者:行者123 更新时间:2023-11-29 15:44:51 27 4
gpt4 key购买 nike

我有一个触发器,仅当 REGEXP 表达式计算结果为 true 时才允许插入。然而,该表达式的计算结果似乎总是为 true。

即使我插入表达式中任何地方都不允许的随机字符,也会插入一行。

正则表达式适用于在线正则表达式检查器。但调用mysql触发器时永远不会失败。

开始

-- find out what is the labelType based on the labelID
SET @labelType = ( SELECT labelTypeID
FROM customer.label
WHERE labelID = NEW.labelID);

IF @labelType = 2 THEN -- 2 = date format in YYYY-MM-DD (ie: 2019-05-05)
IF NEW.labelValue NOT REGEXP '[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])' THEN
SET @err_msg = CONCAT(NEW.labelValue, ' Invalid date format. Please make sure it conforms to YYYY-MM-DD.');

SET @err_msg = left(@err_msg, 128);
SIGNAL SQLSTATE '41000'
SET MESSAGE_TEXT = @err_msg;
END IF;

最佳答案

MySQL 8+ 版本之前的 REGEXP 运算符不支持 \d 表示单个数字。相反,您应该使用[0-9]:

IF NEW.labelValue NOT REGEXP '[12][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])'
THEN
SET @err_msg = CONCAT(NEW.labelValue, ' Invalid date format. Please make sure it conforms to YYYYMMDD.');

这里是一个演示,显示上述正则表达式实际上在 MySQL 5.7 中按预期工作:

Demo

关于mysql - REGEXP 匹配数字在 MySQL 中始终计算为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57187351/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com