MySQL 正则表达式
用 REGEXP / RLIKE 做正则匹配。
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.
基本用法
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' | 完整正则,通常无法用索引 |
正则匹配默认不走索引,数据量大时比 LIKE 前缀还慢。只在 LIKE 表达不了、且数据量可控时才用 REGEXP。