如何使用Trino-SQL将字符串拆分为单个字符?
在AWS Athena(Trino-SQL)中拆分字符串为单个字符
问题原因
你当前使用的regexp_split(s.str,'\D')逻辑错误:\D是正则表达式中的非数字字符匹配符,它会将所有非数字字符当作分隔符来拆分字符串。而你的测试字符串www.google.com中没有任何数字,所以拆分后得到的全是空字符串,这就是exploded_value无值的原因;同时原字符串共有15个非数字字符,因此生成了15行空结果。
解决办法
方法1:使用正则零宽度断言拆分
利用正则的零宽度反向断言,在每个字符之间插入拆分点,再过滤掉开头的空值:
select s.str as original_str, u.str as exploded_value from (select 'www.google.com' as str) AS s cross join unnest(regexp_split(s.str, '(?<=.)')) as u(str) where u.str != '';
方法2:通过序列+子字符串提取(更可靠)
生成从1到字符串长度的整数序列,再用substr逐个提取对应位置的字符,这种方法逻辑更清晰,也不会产生空值:
select s.str as original_str, substr(s.str, pos, 1) as exploded_value from (select 'www.google.com' as str) AS s cross join unnest(sequence(1, length(s.str))) as t(pos);
内容的提问来源于stack exchange,提问作者CaseyR
相关产品推荐
相关产品推荐

