MySQL正则表达式
概述
MySQL通过REGEXP和RLIKE运算符为字符串数据中的模式匹配提供正则表达式支持。正则表达式是复杂模式匹配的强大工具。
正则表达式基础
模式匹配:匹配文本中的特定模式 通配符:灵活匹配的特殊字符 锚点:字符串中匹配的位置 字符类:要匹配的字符集
REGEXP运算符
基本语法
sql
-- REGEXP (case-sensitive by default)
-- RLIKE is synonym for REGEXP
-- NOT REGEXP for negative matchREGEXP与LIKE比较
sql
-- LIKE uses simple wildcards
-- Matches: iPhone, smartphone, telephone
-- REGEXP uses powerful patterns
-- Matches: iPhone, smartphone, telephone, phone
-- Multiple patterns with REGEXP
-- Matches: iPhone, laptop, tablet
-- Equivalent with LIKE would require OR正则表达式元字符
常用元字符
| 模式 | Description / 描述 | Example / 示例 |
|---|---|---|
| 字符串开始 | ^Hello | |
| 字符串结束 | World$ | |
| 任何单个字符 | a.b | |
| 或运算符 | `a | b` |
| 零次或多次 | a* | |
| 一次或多次 | a+ | |
| 零次或一次 | a? | |
| 字符类 | [a-z] | |
| 否定字符类 | [^a-z] | |
| 转义字符 | \. \* |
示例
sql
-- Start of string
-- End of string
-- Any character
-- OR operator
-- Repetition
-- Optional字符类
预定义类
| 类 | Description / 描述 |
|---|---|
| 字母数字 | |
| 字母 | |
| 数字 | |
| 小写 | |
| 大写 | |
| 空格 | |
| 标点 |
示例
sql
-- Alphanumeric
-- Digits
-- Alphabetic
-- Custom character class
-- Range in character class
-- Negated character class实用示例
邮箱验证
sql
-- Simple email pattern
-- More specific pattern电话号码匹配
sql
-- Match US phone numbers
-- Match various phone formats产品代码
sql
-- Match product codes like PROD-123
-- Match SKU patterns文本搜索
sql
-- Find words starting with specific letters
-- Find URLs in text
-- Find mentions (@username)REGEXP_REPLACE函数
MySQL 8.0+支持REGEXP_REPLACE进行替换。
sql
-- Replace digits with X
-- Returns: ProductXXX
-- Remove non-alphanumeric characters
-- Returns: Item123
-- Format phone numbers
-- Returns: (555) 123-4567
-- Replace multiple spaces
-- Returns: Too many spacesREGEXP_LIKE / REGEXP_LIKE
简单模式匹配,无需完整正则表达式支持。
sql
-- REGEXP_LIKE for simple patterns
-- Similar to LIKE but uses REGEXP engine
-- Case-insensitive matching性能考虑
REGEXP性能
sql
-- REGEXP can be slow on large datasets
-- Consider using indexed columns first
-- Efficient pattern
-- LIKE uses index if possible, REGEXP refines
-- Avoid REGEXP with leading wildcards
-- Poor: (can't use index)
-- Better: (can use index)替代方法
sql
-- Use SUBSTRING for fixed patterns
-- Use LEFT for prefix matching
-- Use FULLTEXT for text search高级模式
捕获组
sql
-- Extract parts using REGEXP_SUBSTR (MySQL 8.0+)
-- Returns: letters=PROD, numbers=123单词边界
sql
-- Match whole words
-- Match word at start of string重复量词
sql
-- Exact match {n}
-- Range match {n,m}
-- Minimum match {n,}REGEXP区分大小写
sql
-- Case-sensitive (default)
-- Case-insensitive (using BINARY)
-- Case-insensitive pattern
-- Convert to lowercase常见用例
数据验证
sql
-- Validate postal codes
-- Validate credit card format数据清理
sql
-- Remove special characters
-- Standardize phone formats模式提取
sql
-- Extract domain from email小结
MySQL中的正则表达式提供:
强大的模式匹配:比LIKE更复杂的模式 灵活匹配:通配符、字符类、锚点 字符串函数:REGEXP_REPLACE、REGEXP_SUBSTR(MySQL 8.0+) 搜索功能:邮箱、电话、URL验证
处理大型数据集时考虑性能并使用适当的索引。
上一个:NULL值
下一个:事务