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
    
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐