概念
正则表达式是对字符串操作的一种逻辑公式,就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串”用来表达对字符串的一种过滤逻辑。
1、正则匹配
操作符 | 描述 |
---|---|
~ | 匹配正则表达式,大小写敏感 |
~* | 匹配正则表达式,大小写不敏感 |
!~ | 不匹配正则表达式,大小写敏感 |
!~* | 不匹配正则表达式,大小写不敏感 |
xieyuheng=# select 'xieyuheng,谢宇恒' ~ '[A-z]'; --字符串包含英文字母
?column?
----------
t
(1 row)
xieyuheng=# select 'xieyuheng' ~ '[^A-z]';--字符串包含不是英文字母的内容
?column?
----------
f
(1 row)
xieyuheng=# select '谢宇恒' ~ '[\u4E00-\u9FA5]';--字符串包含中文
?column?
----------
t
(1 row)
2、正则替换
xieyuheng=# select regexp_replace('xieyuheng,谢宇恒,','[A-z,]','','g');--替换字符串内的英文字母及','为''
regexp_replace
----------------
谢宇恒
(1 row)
xieyuheng=# select regexp_replace('xieyuheng,谢宇恒,','[^A-z]','','g');--替换字符串内不是英文字母的内容为''
regexp_replace
----------------
xieyuheng
(1 row)
xieyuheng=# select regexp_replace('xieyuheng,谢宇恒,','[^\u4E00-\u9FA5]','','g');--替换字符串内不是中文的内容为''
regexp_replace
----------------
谢宇恒
(1 row)
3、正则提取
xieyuheng=# select regexp_matches('xieyuheng,谢宇恒,','[\u4E00-\u9FA5]','g');
regexp_matches
----------------
{谢}
{宇}
{恒}
(3 rows)
xieyuheng=# select regexp_matches('xieyuheng,谢宇恒,','[A-z]','g');
regexp_matches
----------------
{x}
{i}
{e}
{y}
{u}
{h}
{e}
{n}
{g}
(9 rows)
xieyuheng=# select regexp_split_to_array('xieyuheng,谢宇恒',',');
regexp_split_to_array
-----------------------
{xieyuheng,谢宇恒}
(1 row)
xieyuheng=# select regexp_split_to_table('xieyuheng,谢宇恒',',');
regexp_split_to_table
-----------------------
xieyuheng
谢宇恒
(2 rows)