MySql中的正则表达式

时间:2012-09-11 15:33:22

标签: mysql regex

在MySql中(我使用的是5.1.48),以下正则表达式返回true,即1

SELECT '10-5' REGEXP '10-5' as temp;
SELECT '10/5' REGEXP '10/5' as temp;
SELECT '1*5' REGEXP '1*5' as temp;

但是,以下表达式返回false,即0

SELECT '10+5' REGEXP '10+5' as temp;
SELECT '10*5' REGEXP '10*5' as temp;

  

在常规中使用特殊字符的文字实例   表达式,前面有两个反斜杠(\)字符。 MySQL   解析器解释其中一个反斜杠和正则表达式   图书馆解释了另一个。

在前两个语句中转义+*会返回true,即1,如下所示。

SELECT '10+5' REGEXP '10\\+5' as temp;
SELECT '10*5' REGEXP '10\\*5' as temp;

如果是这种情况,那么为什么{1}}在以下语句中(第一个片段中的最后一个)需要转义?

*

返回SELECT '1*5' REGEXP '1*5' as temp; true而不转义1,以下类似内容(第二个代码段中的最后一个)返回*

false

需要转义SELECT '10*5' REGEXP '10*5' as temp; 。为什么呢?

1 个答案:

答案 0 :(得分:2)

如您所知,未转义的星号表示“前面的字符为零或更多”,因此“1 * 5”表示“任意数量的1,后跟5”。

关键是来自the doc的信息:

 A REGEXP pattern match succeeds if the pattern matches anywhere in the value being tested. (This differs from a LIKE pattern match, which succeeds only if the pattern matches the entire value.)

因此,“1 * 5”(“任意数量的1,后跟5”)将匹配字符串“1 * 5”,只看到“5”。 “10 * 5”(“1,后跟任意数量的0,后跟5”)与字符串“10 * 5”不匹配,因为“*”字符将其分解。

希望有所帮助。