sql也提供了对字符串进行正则分割,取特定字符的函数——regexp_substr()
regexp_substr()函数格式如下:
regexp_substr(str, pattern, position, occurrence, modifier)
其中:
str:待分割的字符串或者字段值;
pattern:匹配的正则表达式,pattern = '[^___]+',下划线的内容就是需要分割的字符;
position:匹配的起始位置(默认为1);
occurrence:取第几个匹配的字符串(默认为1);
modifier :是否区分大小写,‘i’不区分大小写,‘c’区分大小写(默认为‘c’)
例如:
regexp_substr('hello world!', '[^o]+', 1, 1, 'i')
输出结果为:
hell
实例
使用的数据如下:
我们现在把字符串形式的day字段转换成日期格式yyyy-mm-dd,首先根据 ':' 分割字符串,然后把前三个匹配的字符串拼接起来,生成所需求的字符串。
sql语句如下:
select day,
num,
regexp_substr(day, '[^:]+', 1, 1, 'i') || '-' ||
regexp_substr(day, '[^:]+', 1, 2, 'i') || '-' ||
regexp_substr(day, '[^:]+', 1, 3, 'i') day_new
from test_regexp_substr
输出结果如下: