Mysql中正则表达式Regexp常见用法

Mysql中Regexp常见用法

  • 模糊匹配,包含特定字符串
# 查找content字段中包含“车友俱乐部”的记录
select * from club_content where content regexp '车友俱乐部'

# 此时的regexp与like的以下用法是等同的
select * from club_content where content like '%车友俱乐部%'
  • 模糊匹配,以特定字符串开头
# 查找content字段中以“车友”开头的记录
select * from club_content where content regexp '^车友'

# 此时的regexp与like的以下用法是等同的
select * from club_content where content like '车友%'
  • 模糊匹配,以特定字符串结尾
# 查找content字段中以“车友”结尾的记录
select * from club_content where content regexp '车友$'

# 此时的regexp与like的以下用法是等同的
select * from club_content where content like '%车友'
  • 模糊匹配,或关系
# 查找content字段中包含“心得”、“分享”或“技术贴”
select * from club_content where content  REGEXP '心得|分享|技术贴'
  • 模糊匹配,不包含单个字符
# 查找content字段中不包含“车”字、“友”字的记录
select * from club_content where content  REGEXP [^车友]

这个结果跑出来一看大吃一惊,竟然把所有记录给跑出来,这是为什么呢?
因为一旦加了这个方括号"[]",它就把里面的内容拆成单个的字符再匹配,它会逐个字符去匹配判断是不是等于“车”,或者是不是等于“友“,返回的结果是一组0、1的逻辑值。

如果想匹配不包含特定字符串,该怎么实现呢?

  • 模糊匹配,不包含特定字符串
# 查找content字段不包含“车友”字符串的记录
select * from club_content where content not REGEXP '车友'

欢迎关注微信公众号“数据分析师手记”
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/fwj_ntu/article/details/82896169