列的值是这样的:
["a", "b", "c(d, e)"]
这里的值是字符串类型。我希望将字符串转换为数组,并尝试使用 split (column_name, ',')
。但是,由于数组中的元素包含逗号符号(例如,"c(d, e)"
),因此效果不佳。有没有其他方法可以将字符串转换为数组?
答案 0 :(得分:0)
在这种情况下,您只能在双引号之间用逗号分隔。
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)"]