sql - 如何在配置单元中将字符串转换为数组?
问题描述
该列的值是这样的:
["a", "b", "c(d, e)"]
这里的值是字符串类型。我希望将字符串转换为数组,并尝试使用split (column_name, ',')
. 然而,由于数组中的元素包含逗号符号(例如,"c(d, e)"
),它不能很好地工作。有没有其他方法可以将字符串转换为数组?
解决方案
在这种情况下,您只能在双引号之间用逗号分隔。
REGEXP仅在和'(?<="), *(?=")'
之间匹配带有可选空格的逗号,不包括配额。"
"
(?<=")
是一个零宽度的lookbehind,断言紧接在字符串中当前位置之前的是“
(?=")
是一个零宽度的正向前瞻断言,意味着它应该在当前位置之后
以这种方式拆分后,数组将包含带有引号的元素:' "a"
',您可能想要删除这些引号,使用regexp_replace:
演示:
with your_data as (
select '["a", "b", "c(d, e)"]' as str
)
select split(str, '(?<="), *(?=")') as splitted_array,
element,
regexp_replace(element,'^"|"$','') as element_unquotted
from (
select regexp_replace(str,'^\\[|\\]$','') as str --remove square brackets
from your_data
) d
--explode array
lateral view explode(split(str, '(?<="), *(?=")')) e as element
结果:
splitted_array element element_unquotted
["\"a\"","\"b\"","\"c(d, e)\""] "a" a
["\"a\"","\"b\"","\"c(d, e)\""] "b" b
["\"a\"","\"b\"","\"c(d, e)\""] "c(d, e)" c(d, e)
如果您需要未引用元素的数组,您可以使用 collect_list 再次收集数组。
另一种方法是用一些分隔符替换“,”,删除所有其他配额和方括号,然后拆分。
演示:
with your_data as (
select '["a", "b", "c(d, e)"]' as str
)
select split(str, '\\|\\|\\|') splitted_array
from (--replace '", ' with |||, remove all quotes, remove square brackets
select regexp_replace(regexp_replace(str,'", *"','|||'),'^\\[|\\]$|"','') as str
from your_data ) d
结果:
splitted_array
["a","b","c(d, e)"]