【问题标题】:how to convert string to array in hive?如何在配置单元中将字符串转换为数组?
【发布时间】:2021-06-07 05:04:54
【问题描述】:

列的值是这样的:

["a", "b", "c(d, e)"]

这里的值是字符串类型。我希望将字符串转换为数组,并尝试使用split (column_name, ',')。但是,由于数组中的元素包含逗号符号(例如,"c(d, e)"),因此效果不佳。有没有其他方法可以将字符串转为数组?

【问题讨论】:

    标签: sql arrays split hive hiveql


    【解决方案1】:

    在这种情况下,您只能在双引号之间用逗号分隔。

    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)"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      相关资源
      最近更新 更多