mysql 中正则表达式通过 regexp
或 rlike
操作符实现(两者等价),用于在 where
子句中进行复杂的字符串模式匹配。以下是核心用法和示例:
一、基础语法
select column_name from table_name where column_name regexp 'pattern'; -- 或 where column_name rlike 'pattern';
二、常用元字符
元字符 | 说明 | 示例 |
---|---|---|
^ | 匹配开头 | '^a' → 以 “a” 开头 |
$ | 匹配结尾 | 'z$' → 以 “z” 结尾 |
. | 匹配任意单个字符 | 'a.c' → “abc”, “axc” |
[...] | 字符集合 | '[aeiou]' → 匹配任一元音 |
[^...] | 排除字符集合 | '[^0-9]' → 非数字字符 |
* | 前一个字符0次或多次 | 'ab*c' → “ac”, “abbc” |
+ | 前一个字符1次或多次 | 'ab+c' → “abc”, “abbc” (排除"ac") |
{n} | 前一个字符n次 | 'a{3}' → “aaa” |
| | 或操作 | 'cat|dog' → “cat” 或 “dog” |
三、实际示例
匹配以数字开头的字符串
select name from products where name regexp '^[0-9]';
匹配包含特定单词的文本
select content from logs where content regexp 'error|warning';
匹配邮箱格式
select email from users where email regexp '^[a-za-z0-9._%+-]+@[a-za-z0-9.-]+\\.[a-za-z]{2,}$';
匹配连续重复字符
select word from dictionary where word regexp '(.)\\1'; -- 如 "book"('oo')
四、与 like 的区别
特性 | regexp | like |
---|---|---|
功能 | 复杂模式匹配 | 简单通配符 (% , _ ) |
大小写敏感 | 默认不敏感(除非二进制字符串) | 依赖字段排序规则 |
性能 | 通常较慢(全表扫描) | 可能使用索引 |
五、进阶函数(mysql 8.0+)
regexp_replace()
替换匹配的字符串:
select regexp_replace('hello 123', '[0-9]+', 'world'); -- 结果: 'hello world'
regexp_substr()
提取匹配的子串:
select regexp_substr('abc def ghi', '[a-z]+'); -- 结果: 'abc'
regexp_instr()
返回匹配的起始位置:
select regexp_instr('abc123', '[0-9]+'); -- 结果: 4
六、注意事项
- 转义特殊字符:使用双反斜杠
\\
(如\\+
,\\.
)。 - 性能优化:避免在大型表上使用
regexp
,优先考虑全文索引或预处理。 - 大小写敏感:如需区分大小写,使用
binary
关键字:
where binary column_name regexp 'pattern';
经典案例:提取文本中的金额
select regexp_substr(description, '[0-9]+\\.[0-9]{2}') as amount from orders where description regexp '[0-9]+\\.[0-9]{2}';
匹配如 "price: 99.99 usd"
中的 99.99
。
到此这篇关于mysql中正则表达式用法的文章就介绍到这了,更多相关mysql正则表达式用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论