Skip to content

MySQL正则表达式

概述

MySQL通过REGEXP和RLIKE运算符为字符串数据中的模式匹配提供正则表达式支持。正则表达式是复杂模式匹配的强大工具。

正则表达式基础

模式匹配:匹配文本中的特定模式 通配符:灵活匹配的特殊字符 锚点:字符串中匹配的位置 字符类:要匹配的字符集

REGEXP运算符

基本语法

sql
-- REGEXP (case-sensitive by default)

-- RLIKE is synonym for REGEXP

-- NOT REGEXP for negative match

REGEXP与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
或运算符`ab`
零次或多次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 spaces

REGEXP_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值

下一个:事务