Mysql 正则表达式失败
Mysql regexp fails
我正在尝试查找 table 客户中名称不包含字母的任何记录。以下是我正在使用的。当 运行 时,它 return 没有找到任何记录。请有人指出我的错误吗?
table customers {
name = Еarnings on thе Intеrnet from
}
SELECT name from customers WHERE name NOT REGEXP '[a-zA-Z]' ;
如果我使用 REGEXP '[a-zA-Z]'
比较字符串,如果字符串中的 任何字符 与该正则表达式中的字母匹配,则它匹配。您显示的字符串确实包含 a、r、n、i、g、s 等字母。其中任何一个都足以满足REGEXP比较。
mysql> select 'Еarnings on thе Intеrnet from' REGEXP '[a-zA-Z]' as ok;
+----+
| ok |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
否定NOT REGEXP
等同于NOT (expr REGEXP pattern)
。它只是将结果 1 反转为 0,或者将 0 反转为 1。
mysql> select 'Еarnings on thе Intеrnet from' NOT REGEXP '[a-zA-Z]' as ok;
+----+
| ok |
+----+
| 0 |
+----+
您说过要匹配不包含字母的名称。我想你的意思是你想匹配包含任何非字母字符的名称,这是一个不同的测试。
mysql> select 'Еarnings on thе Intеrnet from' REGEXP '[^a-zA-Z]' as ok;
+----+
| ok |
+----+
| 1 |
+----+
字符Еµ不在[a-zA-Z]
范围内,表示字符互补范围的方式是使用[^a-zA-Z]
。也就是说,对于方括号内的 ^
字符,如果一个字符不是该范围内的字符之一,则该字符将匹配。
另见 https://dev.mysql.com/doc/refman/8.0/en/regexp.html#regexp-syntax 项下:
- [a-dX], [^a-dX]
回复您的评论:
我测试了检查你提到的字符,包括 space、撇号、点和破折号:
mysql> select 'Mr. Tim O''Toole' regexp '[^a-zA-Z \'.-]' as ok;
+----+
| ok |
+----+
| 0 |
+----+
mysql> select 'Mr. Tim $ O''Toole' regexp '[^a-zA-Z \'.-]' as ok;
+----+
| ok |
+----+
| 1 |
+----+
-
前不需要加反斜杠,但需要特殊处理:
To include a literal - character, it must be written first or last.
这在我链接到的文档中。
我正在尝试查找 table 客户中名称不包含字母的任何记录。以下是我正在使用的。当 运行 时,它 return 没有找到任何记录。请有人指出我的错误吗?
table customers {
name = Еarnings on thе Intеrnet from
}
SELECT name from customers WHERE name NOT REGEXP '[a-zA-Z]' ;
如果我使用 REGEXP '[a-zA-Z]'
比较字符串,如果字符串中的 任何字符 与该正则表达式中的字母匹配,则它匹配。您显示的字符串确实包含 a、r、n、i、g、s 等字母。其中任何一个都足以满足REGEXP比较。
mysql> select 'Еarnings on thе Intеrnet from' REGEXP '[a-zA-Z]' as ok;
+----+
| ok |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
否定NOT REGEXP
等同于NOT (expr REGEXP pattern)
。它只是将结果 1 反转为 0,或者将 0 反转为 1。
mysql> select 'Еarnings on thе Intеrnet from' NOT REGEXP '[a-zA-Z]' as ok;
+----+
| ok |
+----+
| 0 |
+----+
您说过要匹配不包含字母的名称。我想你的意思是你想匹配包含任何非字母字符的名称,这是一个不同的测试。
mysql> select 'Еarnings on thе Intеrnet from' REGEXP '[^a-zA-Z]' as ok;
+----+
| ok |
+----+
| 1 |
+----+
字符Еµ不在[a-zA-Z]
范围内,表示字符互补范围的方式是使用[^a-zA-Z]
。也就是说,对于方括号内的 ^
字符,如果一个字符不是该范围内的字符之一,则该字符将匹配。
另见 https://dev.mysql.com/doc/refman/8.0/en/regexp.html#regexp-syntax 项下:
- [a-dX], [^a-dX]
回复您的评论:
我测试了检查你提到的字符,包括 space、撇号、点和破折号:
mysql> select 'Mr. Tim O''Toole' regexp '[^a-zA-Z \'.-]' as ok;
+----+
| ok |
+----+
| 0 |
+----+
mysql> select 'Mr. Tim $ O''Toole' regexp '[^a-zA-Z \'.-]' as ok;
+----+
| ok |
+----+
| 1 |
+----+
-
前不需要加反斜杠,但需要特殊处理:
To include a literal - character, it must be written first or last.
这在我链接到的文档中。