mysql必知必会 ——正则表达式

目的:在mysql where子句中使用正则表达式来更好的控制数据的过滤。


一.基本字符匹配:

1.检索name包含文本san的所有行:

        select * from test where name regexp 'san';


2.知道'.'是正则表达式语言中的一个特殊的字符,他表示匹配任意一个字符,

如:select * from test where name regexp '.0';


3.mysql中的正则表达式匹配不区分大小写,如要区分大小写可使用关键字:binary

如:不区分大小写:select * from test where name regexp 'hh';


区分大小写:select * from test where name regexp binary 'hh';


4.进行or匹配:select * from test where age regexp '2|3|12';  包含2或包含3或包含12


5.匹配特定字符:可通过指定一组用[和]括起来的字符完成:

select * from test where name regexp '[123]zh';    [123]意思是匹配1或2或3

二.匹配范围:

1.集合可以用来定义要匹配的一个或多个字符:

如:[0123456789]        匹配数字0到9 ; 也可使用-,如:[0-9]  意思一样。

同理[a-z] 匹配任意字母。

select * from test where name regexp '[a-z]d';   


三.匹配特殊字符

转义:使用\\进行转义。

如:1)匹配.   ,则为\\.    如:select * from test where name regexp '\\.';    name中包含.的记录。


    2)匹配|     ,用\\|   如:select * from test where name regexp '\\|';

     3) 匹配(  ,用\\(  如:select * from test where name regexp '\\(';

    3)匹配[]    ,用\\[    \\]    如:select * from test where name regexp '\\[*\\]';    *表示0个或多个匹配。


   4)匹配-     ,用\\-



四.匹配字符类


如:

    1)检索name字段中包含数字的记录:select * from test where name regexp '[[:digit:]]';

    


五.匹配多个实例

1)使用*:         select * from test where name regexp '\\[*\\]';    *表示0个或多个匹配[。

2)使用?:  select * from test where name regexp 'zhs?';           

          s后的?使s可选,因为?匹配它前面的字符0次或多次。

 

3)使用+:    select * from test where name regexp '\\.+';



4)使用{n,}


六.定位符

为了匹配特定位置的文本,需要使用下表中的定位符:


如:1)检索name以数字开头(文本开头)的记录:

 select * from test where name regexp '^[[:digit:]]';


2)检索name以n结尾(文本结尾)的记录:select * from test where name regexp 'n$';


3)检索以2开头的词的记录:

select * from test where name regexp '[[:<:]]2';


4)检索以d结尾的词的记录:

select * from test where name regexp 'd[[:>:]]';


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值