MySQL 正则表达式

用 REGEXP / RLIKE 做正则匹配。

Beginner
Key PointsREGEXP 是包含匹配(默认不锚定);MySQL 8.0 支持 REGEXP_LIKE 等函数。

基本用法

SQL
SELECT * FROM users WHERE username REGEXP '^a';       -- 以 a 开头
SELECT * FROM users WHERE email RLIKE '\\.com$';       -- 以 .com 结尾
SELECT * FROM users WHERE username REGEXP '[0-9]';     -- 含数字
Output
+----+----------+-----+
| id | username | age |
+----+----------+-----+
|  1 | alice    |  29 |
+----+----------+-----+

与 LIKE 的区别

写法说明
LIKE 'a%'简单通配,可用索引(前缀)
REGEXP '^a'完整正则,通常无法用索引
Regex matches usually can't use an index and are slower than a LIKE prefix at scale. Use REGEXP only when LIKE can't express the pattern and the data set is small.

Friends & Partners