提问人:archjkeee 提问时间:8/25/2023 最后编辑:archjkeee 更新时间:8/26/2023 访问量:79
SQL split() 中的正则表达式,用于将括在方括号中的逗号分隔字符串转换为数组,并从每个元素中删除周围的引号
Regex in SQL split() to convert a comma separated string enclosed in square brackets into an array and remove the surrounding quotes from each element
问:
我有字符串数据列,其值如下所示:
- ["some val1"]
- []
- ["some val2", "some_val3"]
- single value without brackets and quotes
- [[]
- ["val with "quote 1", "val with "quote and bracket["]
我想将值转换为数组,因此数组列将如下所示:
- 0: some val1
- 0: null
- 0: some val2
1: some val3
- 0: single value without brackets and quotes
- 0: [
- 0: val with "quote 1
1: val with "quote and bracket[
我怎样才能将这些数据拆分成一个数组(我假设,spark-sql函数可以用于此)?split()
目前我使用此代码,但它并没有从每个元素中删除周围的引号 + 我觉得总的来说,它可以通过仅使用传递给函数的简单正则表达式而不使用 / 来完成。split()
ltrim
rtrim
with cte as
(select '["some val1"]' as val
union all
select '[]'
union all
select '["some val2", "some_val3"]'
union all
select 'single value without brackets and quotes'
union all
select '[[]'
union all
select '["val with "quote 1", "val with "quote and bracket["]')
select
split(ltrim('[', rtrim(']', val)), ',') as array_val
from cte
更新:更新的示例数据 + 一些摘要:我只需要删除源值周围的一对括号,并且只需要删除每个元素周围的一对括号。我也尝试了这段代码,但它没有从数组的第二个元素中删除第一个引号:
transform(split(regexp_replace(val, '^[\\[]|[\\]]$', ''), ','), x -> regexp_replace(x, '^["]|["]$', ''))
答:
0赞
JayashankarGS
8/25/2023
#1
我尝试了您的代码并得到了如下所示的输出。
在这里,字符串被包围,如果它是空字符串,则为 no。\"
null
因此,我按如下方式修改了查询并得到了输出。
with cte as
(select '["some val1"]' as val
union all
select '[]'
union all
select '["some val2", "some_val3"]'
union all
select 'single value without brackets and quotes')
select
trim('[]',regexp_replace(val,'"' ,'' )) as array_val,
case
when instr(array_val,',') > 0 then
split(array_val,',')
when len(array_val)==0 then
array(null)
else
array(array_val)
end as nt
from cte
输出:
评论
0赞
archjkeee
8/25/2023
谢谢。但是我只需要删除源值周围的一对括号,并且只需要删除每个元素周围的一对括号
0赞
JayashankarGS
8/25/2023
好的,在问题中添加示例数据。
0赞
archjkeee
8/25/2023
好的,更新了问题。
0赞
JayashankarGS
8/28/2023
@archjkeee 尝试这个,并在 split 和 null 的解决方案中添加 case 语句。select regexp_replace(regexp_replace(val, '^\\["|"\\]$|^\\[|\\]$', ''),'"\\s*,\\s*"',',') as array_val
评论