sql中常用的正则匹配

56 篇文章 11 订阅
55 篇文章 1 订阅

sql的正则匹配


语法:

regexp ‘表达式’

1.直接匹配

字符中能匹配到就返回1,不能匹配到就返回0

> select 'hello' regexp 'he'
> 1
> select 'hello' regexp 'llo'
> 1
> select 'hello' regexp 'hee'
> 0

2.符号’^’

代表开头,需要开头是某个字符

> select 'hello' regexp '^he'
> 1
> select 'hello' regexp '^llo'
> 0

3.符号’$’

代表结尾,需要结尾是某个字符

> select 'hello' regexp 'llo$'
> 1
> select 'hello' regexp 'll$'
> 0

4.符号’.’

代表任意一个字符,可以匹配上任何一个字符

> select 'hello' regexp '.ello'
> 1
> select 'hello' regexp '.lo'
> 1
> select 'hello' regexp '.c'
> 0

5.符号’+’

前面的字符至少出现1次

> select 'hello' regexp 'h+'
> 1
> select 'hello' regexp 'o+'
> 1
> select 'hello' regexp 'c+'
> 0

6.符号’*’

前面的数字至少出现0次

> select 'hello' regexp 'he*'
> 1
> select 'hello' regexp 'c*'
> 1
> select 'hello' regexp 'c*e'
> 1
> select 'hello' regexp 'c*c'
> 0

7.符号’?’

前面的数字最多出现1次

> select 'hello' regexp 'c?c?h'
> 1
> select 'hello' regexp 'h?ello'
> 1
> select 'hello' regexp 'c?c'
> 0

8.符号’()’

代表一个整体,全体匹配

> select 'hello' regexp '(cda)?he'
> 1
> select 'hello' regexp '(helc).o'
> 0

9.符号’[]’

匹配符号内的任何一个字符即可

> select 'hello' regexp '[hege]ello'
> 1
> select 'hello' regexp '[jilsdf]hello'
> 0

注意:

如果想要匹配字符’[’ 或者’]‘,需要把’[‘放在’]‘前,匹配’]'也是同理

> select '[[]]' regexp '[asd[]'
> 1
> select '[[]]' regexp '[[asd]'
> 0
> select '[[]]' regexp '[]asd'
> 1
> select '[[]]' regexp '[asd]]'
> 0

符号[]中可以使用’-'表示区间,表示匹配区间内的数据

> select 'hello' regexp '[a-z]'
> 1

如果匹配’-', 需要放到[]的两端

> select 'asg-' regexp '[-ccc]'
> 1
> select 'asg-' regexp '[cc-c]'
> 0

如果是[^],表示不含[]里的任何字符

> select 'hello' regexp '[^0-9]'
> 1
> select 'hello' regexp '[^a-z]'
> 0

10.符号’|’

匹配分割的任何一个字符

> select 'hello' regexp 'h|c'
> 1
> select 'hello' regexp 'c|g'
> 0

11.符号’{t}’

匹配前面的字符t次

> select 'hello' regexp 'l{2}'
> 1
> select 'hello' regexp 'l{3}'
> 0

符号{t,s}

匹配次数在t-s次均可

> select 'hello' regexp 'l{1,3}'
> 1

举例:

  1. 以app、ios、androd开头的字符串

    > select 'tmma.ctime' regexp '^app|^ios|^androd'
    > 0
    > select 'appa.ctime' regexp '^app|^ios|^androd'
    > 1
    
  2. 以tm或者以re开头,并且以me结尾的字符串

    > select 'tmma.ctime' regexp '^tm.*me$|^re.*me$'
    > 1
    > select 'tmma.ctim' regexp '^tm.*me$|^re.*me$'
    > 0
    
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牧码文

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值