如何使用 reg_extract 或拆分在 Hive 中的特殊字符后打印字符串的第一次出现?
How do I print the first occurence of a string after a special character in Hive using reg_extract or split?
我在蜂巢中遇到了一个很深的困境。我在 Hive 中的数据集如下所示:
##214628##564#7576#7876
#12771#242###256823
###3264###7236473####3
在每个实例中,我只想打印# 之后的第一个字符串。所以输出应该是这样的:
214628
12771
3264
我尝试使用 reg_extract 函数,但很遗憾,我只得到 NULL 值。由于配置单元不支持 reg_substr,因此以下语法不起作用:
to_number(trim(regexp_substr(col_name,'[^#]+',1,1)))
欢迎提出任何建议!
您可以使用 regexp_replace 和 substr 组合。
首先使用 regexp_replace()
.
从字符串中删除所有多次出现的 #
regexp_replace(col,'#+','#') -- for data '#####123##' this will produce '#123#'
然后使用 substr 删除第一个#。然后使用 instr 获取从 first 到 #.
的所有内容
substr(substr(str,2),1, instr(substr(str,2),'#')-1) this will produce '123'
你可以在下面看到整个sql。
select substr(substr(str,2),1, instr(substr(str,2),'#')-1) as result
from (
SELECT regexp_replace('#####123##','#+','#') as str) a
我假设你的开头总是#。如果你只是添加if left(str,1)='#'...
并根据数据处理。
我在蜂巢中遇到了一个很深的困境。我在 Hive 中的数据集如下所示:
##214628##564#7576#7876
#12771#242###256823
###3264###7236473####3
在每个实例中,我只想打印# 之后的第一个字符串。所以输出应该是这样的:
214628
12771
3264
我尝试使用 reg_extract 函数,但很遗憾,我只得到 NULL 值。由于配置单元不支持 reg_substr,因此以下语法不起作用:
to_number(trim(regexp_substr(col_name,'[^#]+',1,1)))
欢迎提出任何建议!
您可以使用 regexp_replace 和 substr 组合。
首先使用 regexp_replace()
.
regexp_replace(col,'#+','#') -- for data '#####123##' this will produce '#123#'
然后使用 substr 删除第一个#。然后使用 instr 获取从 first 到 #.
的所有内容substr(substr(str,2),1, instr(substr(str,2),'#')-1) this will produce '123'
你可以在下面看到整个sql。
select substr(substr(str,2),1, instr(substr(str,2),'#')-1) as result
from (
SELECT regexp_replace('#####123##','#+','#') as str) a
我假设你的开头总是#。如果你只是添加if left(str,1)='#'...
并根据数据处理。